Python import syntax

It:

import foo as bar 

do the same thing as this?

 bar = __import__('foo') 

Is there a reason to use the latter?

I read someone's elses code, I found the last one and don’t know why they didn’t use the previous syntax

+4
source share
4 answers

Direct use of __import__() is rare, unless you want to import a module whose name is known only at run time.

a source

+6
source

Both statements do the same. The only reason to use the latter syntax is to not know the module name in advance.

+5
source

From Import Python Modules from Fredrik Lundh:

Python provides at least three different ways to import modules. You can use the import , from statement or the built-in __import__ . (There are more far-fetched ways to do this too, but that is beyond the scope of this small note.)

...

X = __import__ ('X') works like import X , with the difference that you
1) pass the module name as a string and
2) explicitly assign it to a variable in your current namespace.

+2
source

As others said, the two forms are semantically the same. Later ( __import__('foo') ) is used when the module name is not known before execution. The most common examples of this are modules named in the configuration file or in the plugin loading system. Django configuration files, for example, define plug-in modules as strings (for example, some_plugin = 'foo.plugin' ) in the python configuration file, and Django loads these modules using __import__ .

+1
source

All Articles