Import Python into __init __ ()

I need to import into the __init__() method (because I need to run this import only when I am an instance of the class).

But I don’t see that imports are outside of __init__() , is this an area limited to __init__ ? how to do it?

+6
source share
4 answers

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.

+8
source

You can simply import it again to other places that you need - it will be cached after the first time, so it is relatively inexpensive.

Alternatively, you can change the current global namespaces with something like globals()['name'] = local_imported_module_name .

EDIT . For the record, although using the globals() function will certainly work, I think the “cleaner” solution would be to declare the module name global and then import it, as mentioned by a few more answers.

+4
source

The import statement makes imported names available only for the current scope. import foo import foo creates foo , which is displayed only in the __init__ method.

You can either add import foo to any method that needs to access the module, or if you wrote the import again compared to the global to import it into the module area.

 class Wayne(object): def __init__(self): global foo import foo 
+3
source

If you want the result of your import to be visible to other objects of the class, you need to assign the resulting object from your import to a class or instance variable

For instance:

 >>> class Foo(object): ... def __init__(self): ... import math ... self.bar = math.pi ... def zoo(self): ... return self.bar ... >>> a = Foo() >>> a.zoo() 3.141592653589793 
+2
source

All Articles