I discovered an annoying behaviour of reload()
(both Python 2 builtin and from importlib
) that I am trying to walkarround.
I am analysing data in interactive Python interpreter. My code is organised in modules (both Python 2 and 3 compatible) which I often change.
Restarting the interpreter is not feasible due to long time of loading data, so I prefer to recursively reload modules instead.
The problem is that reload()
updates the code but preserves the module global scope (it applies to Python 3 importlib.reload()
as well). It seems to be harmful for methods using super()
(it took me a while to realise what is going on).
The minimal failing example for a module bar.py:
class Bar(object):
def __init__(self):
super(Bar, self).__init__()
is:
>>> import bar
>>> class Foo(bar.Bar):
... pass
...
>>> reload(bar)
<module 'bar' from '[censored]/bar.py'>
>>> Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[censored]/bar.py", line 3, in __init__
super(Bar, self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type
I may:
- use
super()
without arguments in Python 3 manner (which is not compatible with Python 2), - abandon it and call
Bar.__init__(self)
instead (which is harder to maintain and discouraged), - monkey-patch the class adding a class attribute containing a circular reference to the class itself.
None of the ideas I like. Is there any other way of dealing with the issue?