Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Dispose Pattern in Python?

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?

like image 785
Abhash Kumar Singh Avatar asked Oct 26 '25 09:10

Abhash Kumar Singh


1 Answers

Python has:

  • try ... finally, which is equivalent to the similar construction in C#;
  • the 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__.

like image 64
George Sovetov Avatar answered Oct 28 '25 22:10

George Sovetov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!