Relative vs Absolute Imports in Python
While you can put simple projects in a single file, most Python development projects will require multiple files to keep them manageable. That means you need a way to import one file into another. However, many Pythonistas find importing files confusing. Fortunately, it is easy if you know the difference between the various Python import statements.
What is Importing?
Importing refers to allowing a Python file or a Python module to access the script from another Python file or module. You can only use functions and properties your program can access. For instance, if you want to use mathematical functionalities, you must import the math package first. This is because you must define everything you want to use in Python before you use them.
For example, Python would give a NameError
for the following code:
myPi = math.pi
This is because neither the math
object nor its properties and methods are natively available to the language itself. To use the math
object, you must import it first.
import math
myPi = math.pi
print myPi
The import
statement adds the object to the current scope of your program.
How Imports Work
The import
statements