Published on

Python "import module as *"

Authors
  • avatar
    Name
    Tinker Assist
    Twitter

What does "import module as *" do in Python?

In short, It imports all variables, functions, classes, into the current module as if they were declared in the current module. Generally speaking, when you use "as" to append to an import in Python, you are creating an alias for the module name.

Commonly, libraries like pandas will be imported as "import pandas as pd", so that you can call a pandas method with pd.function() rather than pandas.function().

Example

If we create two files in the same folder on our desktop, some_module.py and base_module.py, we can see this in action.

Import modules folder structure

# some_module.py
x = 1
y = 2
# base_module.py
import some_module as *

print(x)
print(y)

If we run base_module.py from the folder both of these modules are in, we will get the following returned

C:\projects\import-example> python base_module.py
1
2

This is because the x and y variables from some_module.py are effectively brought into the base_module.py module.

On the other hand, if we didn't use the special import syntax, we would get an error as shown below

# some_module.py
x = 1
y = 2
# base_module.py
import some_module

print(x)
print(y)

Running in the terminal, we get the below result

C:\projects\import-example> python base_module.py
line 3, in <module>
    print(x)
NameError: name 'x' is not defined

To fix this, we would have to use the module name to reference that modules variables as is normal practice.

import some_module

print(some_module.x)
print(some_module.y)
C:\projects\import-example> python base_module.py
1
2