3

Is it possible to remove a class definition from a running instance of Python?

I have a Python interpreter built into my C++ that I'd like to add and remove classes depending on the current state of the application. For example, if I have a Menu hierarchy that has a corresponding class defined for that menu, I'd like to remove that class if the menu is not visible.

One possible solution is to put the class in a module and unload that module (How do I unload (reload) a Python module?), but I'm wondering if there's an easier way.

Community
  • 1
  • 1
Michael Kelley
  • 3,579
  • 4
  • 37
  • 41
  • 2
    Could you add your main goal for doing something like this? Is it to keep memory usage down, for example? The reason being is: this seems like needless complexity to me :), so I'd like to know the use case you found where doing this is actually useful. – Derek Litz Dec 09 '11 at 01:36
  • 1
    I'm also curious about the use case. – Raymond Hettinger Dec 09 '11 at 05:28
  • FWIW, one use case is that you have `reload()`ed a module - say, because you are iterating on a Jupyter notebook, and are also changing the modules - and you have a class defined in the notebook that inherits from classes in that module. This seems to be the only way to fix up the inheritance structure. – Kristoffer Sjöö Mar 27 '20 at 12:44

1 Answers1

10

Use del on the reference to the class.

>>> class Example(object):
...     pass
... 
>>> Example
<class '__main__.Example'>
>>> del Example
>>> Example
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Example' is not defined
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • I think there is a long-running “feature” that, even when the running program has no references to a class, its memory is not released for the duration of the program. – tzot Dec 24 '11 at 19:51