The module is loaded. It just isn’t in the place where you’re looking for it.
The scoping of class
blocks is a little weird in Python. When the interpreter first encounters the block, it runs the code (i.e., the def
statements are creating new functions, assignments are assigning, etc.) in a temporary, local scope. However, after it finishes doing that, it gathers up those local variables and uses them to create the class object.
import
is a form of assignment in Python, so in your example code, time
becomes a local variable (naming the standard library time
module, which has now been imported and cached). So when the class is created, it will have a time
attribute corresponding to that:
>>> dir(Sample)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'call', 'time']
>>> Sample.time
<module 'time' (built-in)>
But the code in the call
method is expecting a global variable instead. At this point, time
is not a global variable. Sample
is, and it has that attribute; so we could access it like Sample.time.sleep(3)
.
However, it would be better to just put import
s at the top of the file, as is the normal practice. Deferred import
s are a special purpose tool.