Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between import and __import__ in Python

I was taking a look at some commit of a project, and I see the following change in a file:

-       import dataFile
+       dataFile = __import__(dataFile)

The coder replaced import dataFile by dataFile = __import__(dataFile).

What exactly is the difference between them?

like image 371
Oscar Mederos Avatar asked Mar 14 '13 04:03

Oscar Mederos


People also ask

What is __ import __ Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.

What is the difference between import and from import * in Python?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.

What are the two types of import in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)

What is Python __ name __?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


1 Answers

import dataFile 

translates roughly to

dataFile = __import__('dataFile')

Apparently the developer decided that they wanted to use strings to identify the modules they wanted to import. This is presumably so they could dynamically change what module they wanted to import ...

like image 142
mgilson Avatar answered Oct 10 '22 10:10

mgilson