1

Recently, I developed dynamic object in C# ( a small library of sort) that I can link to my python application (excuse my nomenclature if it's not right). I have some IDisposable object that opens the file in the constructor and then closes it in Dispose() method. The file needs to stay open throughout the object's life.

I would expect Dispose() method would be call automatically after last live reference but instead I have to call it explicitly.

  • Python 3.7.3
  • Ubuntu 18.04.2
  • pythonnet 2.4.0
  • mono 5.18.1.28
import clr
clr.AddReference("MyLibrary")
from MyLibrary import DynamicObject

and then use it further in my code:

def foo():
   my_obj = DynamicObject()
   ...
   my_obj().Dispose() # have to call it here
   return

Moreover, the finalizer is not called either. Is there a way to make use of either finalizer or Dispose() method and not call them explicitly or garbage collector from CLR has no idea what is going on in my python script? How python communicates through python.net?

Thank you :- )

Proko
  • 1,871
  • 1
  • 11
  • 23

1 Answers1

1

Dispose doesn't get called automatically. It's there so that whatever uses the class can use it to dispose of unmanaged resources when required. The finalizer will get called automatically, but this will be whenever the garbage collector decides to do it, rather than immediately after the instance goes out of scope.

If you want to make managing your Dispose calls a little easier you can look at the using statement, which is supported by with in Python.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
  • Thanks for the answer. I know the using statement but I'm not sure how can I use it so that the file stays open throughout object's life and I have access to it from every method. Cheers – Proko Aug 12 '19 at 10:37
  • 1
    @mjwills it does not . It has more or less equivalent ```with``` statement – Proko Aug 12 '19 at 10:38
  • Yes, I tried intuitively to do this with '''with''' statement because I thought there would be a smart mapping, however, it does not work with my environment. Now I know it works with IronPython but it's python < 3.5 so I cannot use it. Also, I would like to avoid IronPython in general. Of course, I will accept this answer if there is no way to do it in vanilla python. Thank you :) – Proko Aug 12 '19 at 10:56
  • Also, the finilizer isn't _guaranteed_ to be called at some point? – Proko Aug 12 '19 at 10:58
  • @Proko Correct. It is **not** guaranteed. _Usually_ they will, but it isn't guaranteed. – mjwills Aug 12 '19 at 11:00