Um den Antworten von AlexMartelli und Catskul nachzugehen , gibt es einige wirklich einfache, aber böse Fälle, die verwirrend zu sein scheinenreload
zumindest in Python 2 .
Angenommen, ich habe den folgenden Quellbaum:
- foo
- __init__.py
- bar.py
mit folgendem Inhalt:
init.py:
from bar import Bar, Quux
bar.py:
print "Loading bar"
class Bar(object):
@property
def x(self):
return 42
class Quux(Bar):
object_count = 0
def __init__(self):
self.count = self.object_count
self.__class__.object_count += 1
@property
def x(self):
return super(Quux,self).x + 1
def __repr__(self):
return 'Quux[%d, x=%d]' % (self.count, self.x)
Dies funktioniert einwandfrei ohne reload
:
>>> from foo import Quux
Loading bar
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> Quux()
Quux[2, x=43]
Aber versuchen Sie neu zu laden und es hat entweder keine Wirkung oder korrumpiert Dinge:
>>> import foo
Loading bar
>>> from foo import Quux
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> reload(foo)
<module 'foo' from 'foo\__init__.pyc'>
>>> Quux()
Quux[2, x=43]
>>> from foo import Quux
>>> Quux()
Quux[3, x=43]
>>> reload(foo.bar)
Loading bar
<module 'foo.bar' from 'foo\bar.pyc'>
>>> Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> Quux().count
5
>>> Quux().count
6
>>> Quux = foo.bar.Quux
>>> Quux()
Quux[0, x=43]
>>> foo.Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> foo.Quux().count
8
Der einzige Weg, wie ich sicherstellen konnte, dass das bar
Submodul neu geladen wurde, war reload(foo.bar)
: Die einzige Möglichkeit, auf die neu geladene Quux
Klasse zuzugreifen, besteht darin, sie vom neu geladenen Untermodul zu erreichen und zu greifen. aber das foo
Modul selbst hielt am ursprünglichen Quux
Klassenobjekt fest, vermutlich weil es verwendet from bar import Bar, Quux
(anstatt import bar
gefolgt von Quux = bar.Quux
); Außerdem war die Quux
Klasse nicht mehr mit sich selbst synchronisiert, was nur bizarr ist.
... possible ... import a component Y from module X
" vs "question is ... importing a class or function X from a module Y
". Ich füge eine Bearbeitung zu diesem Effekt hinzu.