Imported names are bound to the current scope, so the import inside the function is bound only to the local name.
If you absolutely need to import something into __init__ , which should then be available worldwide, first mark the imported name as global :
>>> def foo(): ... global sys ... import sys ... >>> sys Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sys' is not defined >>> foo() >>> sys <module 'sys' (built-in)>
but this usually leads to strange and surprisingly difficult searches for errors. Do not do this, just do your import in the module area.
If you need the imported name in other methods of the class, you can also assign the imported name to the instance variable:
class Foo(object): def __init__(self): import os self.join = os.path.join
but again, this is not the best practice to use.
source share