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?
__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.
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.
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)
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.
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With