Let's say we have a class Foo
in file foo.py
like this:
class Foo:
"""Hi, I'm a class"""
Now I want to load that class from another file
from foo import Foo
assert Foo()
great!
Now I know it's not best practice, but we can also use exec
to load the class:
exec(open('foo.py').read())
assert 'Foo' in locals()
nice!
Now let's write a function that gives us a choice, which method we want to use to load the class:
def load_class(exec_load=True):
if exec_load:
exec(open('foo.py').read())
clazz = locals()['Foo']
else:
from foo import Foo
clazz = Foo
return clazz
Now when I run load_class()
, I get a KeyError for Foo
, which means the class was not loaded. This is unexpected, why wouldn't I get to load the class?
However, when I uncomment the local import statement from foo import Foo
like this
def load_class(exec_load=True):
if exec_load:
exec(open('foo.py').read())
clazz = locals()['Foo']
else:
#from foo import Foo
clazz = Foo
return clazz
it works just fine. Even though that line is never reached! load_class(exec_load=False)
of course won't work now because of the missing import...
But how is this possible? How can this one import statement that is never even executed prevent the class from being loaded in the first place?