I have to create a python-wrapper for a C API. I have used ctypes to call into C dlls from python. I am able to create Handle and use it from python. I am looking for Dispose pattern in Python similar to that of C#. Does there exist a Dispose pattern in python?
Python has:
try ... finally, which is equivalent to the similar construction in C#;with statement, which is an analogue of using(... = new ...()) in C#.Note that, unlike C#, with statement accepts already constructed object, calls __enter__ when entering and __exit__ when exiting. I.e., the object is initialized in __init__, the resource is acquired in __enter__ and disposed of in __exit__. Therefore, such an object can be used multiple times.
With contextlib.closing, it's possible to get closer to C#. Acquire the resource in __init__ and dispose of it in the close method. contextlib.closing makes a wrapper which calls close in its __exit__.
In your case, you should make all preparations in __init__, acquire the actual handle in __enter__, and dispose of it in __exit__.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With