Skip to main content

The `import` Statement: Bringing Code into Your Namespace

In our last article, we learned how to organize code into separate files called **[modules]**. Now, we need to master the tool that makes modules useful: the import statement. This statement is the gateway to accessing code from other files and from Python's vast standard library, allowing you to build powerful applications without reinventing the wheel.


πŸ“š Prerequisites​

You should understand the concept of a Python module:

  • A module is a .py file containing Python code.

🎯 Article Outline: What You'll Master​

In this article, you will learn:

  • βœ… Basic import: The standard way to import an entire module.
  • βœ… The from ... import Statement: How to import specific functions or classes from a module directly into your current namespace.
  • βœ… Aliasing with as: How to rename modules and functions on import to avoid name conflicts or for brevity.
  • βœ… Importing Best Practices: The right way to structure your imports for clean, readable code, including the dreaded wildcard import.

🧠 Section 1: The Standard import​

The most basic way to use the import statement is to import an entire module. This brings the module's contents into your script, but it keeps them within the module's own namespace.

Let's use the math module, which is part of Python's standard library.

# basic_import.py

import math

# To access functions from the math module, we must use the 'math.' prefix.
pi_value = math.pi
square_root = math.sqrt(25)

print(f"The value of Pi is: {pi_value}")
print(f"The square root of 25 is: {square_root}")

# Output:
# The value of Pi is: 3.141592653589793
# The square root of 25 is: 5.0

This is the safest and clearest way to import. It's explicit where pi and sqrt are coming fromβ€”they belong to the math module.


πŸ’» Section 2: Importing Specific Names with from ... import​

Sometimes, you only need one or two things from a module, and typing the module's name repeatedly can be tedious. The from ... import statement allows you to import a specific function, class, or variable directly into your current script's namespace.

# from_import.py

# Import only the sqrt and pi objects from the math module.
from math import sqrt, pi

# Now we can use them directly without the 'math.' prefix.
pi_value = pi
square_root = sqrt(25)

print(f"The value of Pi is: {pi_value}")
print(f"The square root of 25 is: {square_root}")

This is more concise, but it can also be less clear. If you see sqrt(25) in a large file, you might not immediately know where the sqrt function came from without looking at the imports at the top of the file.


πŸ› οΈ Section 3: Renaming with as (Aliasing)​

What if you want to import a module, but its name is very long, or it conflicts with a name you're already using? You can solve this by creating an alias with the as keyword.

This is extremely common in the data science world, where libraries like numpy and pandas have conventional, shortened aliases.

# aliasing_import.py

# Import the 'math' module and give it the alias 'm'.
import math as m

# Import the 'count_vowels' function from our previous module and alias it.
from string_utils import count_vowels as cv

pi_value = m.pi # Use the alias 'm'
vowel_count = cv("Programming") # Use the alias 'cv'

print(f"The value of Pi is: {pi_value}")
print(f"The word 'Programming' has {vowel_count} vowels.")

# Output:
# The value of Pi is: 3.141592653589793
# The word 'Programming' has 3 vowels.

Aliasing is a powerful tool for writing clean and conventional Python code.


πŸš€ Section 4: Import Best Practices​

How you structure your imports matters for code readability and maintainability.

4.1 - Import Order​

According to the official Python style guide (PEP 8), imports should always be at the top of the file and grouped in the following order:

  1. Standard Library Imports: (e.g., math, os, sys)
  2. Third-Party Library Imports: (e.g., requests, numpy, pandas)
  3. Local Application/Module Imports: (Code from your own project)

Separate each group with a blank line.

# Correct import order

# 1. Standard library
import os
from datetime import datetime

# 2. Third-party libraries
import pandas as pd
import requests

# 3. Local application
from my_project.utils import helper_function
from . import local_module

4.2 - The Problem with Wildcard Imports​

It's possible to import everything from a module using an asterisk (*). This is called a wildcard import.

# wildcard_import.py

from math import * # <-- AVOID DOING THIS

# Now all names from math are in our namespace
print(pi)
print(sqrt(25))
print(sin(0))

You should almost never do this. Wildcard imports dump all the names from the imported module into your current namespace. This has two major problems:

  1. It hides the source. It's impossible to know where pi or sqrt came from without knowing the entire contents of the math module.
  2. It can cause name collisions. What if you already had a variable named pi? The wildcard import would overwrite it silently, potentially causing subtle and hard-to-find bugs.

Always be explicit. Prefer import math or from math import specific_name.


✨ Conclusion & Key Takeaways​

The import system is the foundation of code sharing and organization in Python. Using it correctly is a hallmark of a professional developer.

Let's summarize the key takeaways:

  • import module: The safest, most explicit way to import. Access content via module.name.
  • from module import name: More concise, but makes the origin of name less obvious.
  • import module as alias: Perfect for long module names or to follow common conventions.
  • Order Your Imports: Group them: standard library, third-party, then local.
  • Avoid Wildcard Imports: from module import * pollutes your namespace and should be avoided.

Challenge Yourself: Python has a built-in module called random. Import this module and use its randint(a, b) function, which returns a random integer between a and b (inclusive). Then, try importing only the choice(sequence) function (which picks a random element from a list) and use it on a list of your favorite foods.


➑️ Next Steps​

You now know how to create modules and import them in various ways. Next, we'll build on this knowledge to structure our own projects by "Creating Your Own Modules."

Happy importing!


Glossary (Python Terms)​

  • Standard Library: The library of modules that comes bundled with every Python installation.
  • Third-Party Library: A library created by other developers that you can install (usually with pip).
  • Alias: An alternate name given to a module or function during import using the as keyword.
  • Wildcard Import: An import statement of the form from module import *, which imports all public names from a module into the current namespace.

Further Reading (Python Resources)​