How to Import a Library in Python
What you’ll build or solve
You’ll import a library the right way in Python, then use it without ImportError or confusing name clashes.
When this approach works best
This approach works best when you:
Learn Python on Mimo
- Add a new library (like
requests) and want to import it in a script. - Organize your code into multiple files and import between them.
- Work in a project where the same code needs to run on different machines.
Avoid this approach when:
- You paste one small snippet into a Python REPL once. You can still import there, but you may not need project structure.
Prerequisites
- Python 3 installed
- You know what variables are
- You can run a
.pyfile from the terminal or your editor
Note: People often say “library,” “module,” and “package” loosely to mean “something you can import.” This guide uses “library” to mean any importable code.
Step-by-step instructions
1) Import a built-in library
Built-in libraries ship with Python, so you can import them without installing anything.
Python
import math
print(math.sqrt(49))
If it runs without installation, it’s part of the standard library.
2) Import a third-party library you installed
Third-party libraries come from pip. Install first, then import. For detailed pip usage and troubleshooting, see the guide on installing modules.
Install:
Bash
python -m pip install requests
Then use it:
Python
import requests
resp = requests.get("https://example.com", timeout=10)
print(resp.status_code)
What to look for:
Use python -m pip so you install into the same Python that runs your script.
3) Import only what you need
This keeps your code shorter and clearer.
Python
from math import sqrt, pi
print(sqrt(81))
print(pi)
If you want a shorter name, use an alias:
Python
import datetime as dt
print(dt.date.today())
Aliases are common with longer names, like:
Python
import numpy as np
4) Import your own code from another file
Create two files in the same folder.
utils.py:
Python
def greet(name: str) -> str:
return f"Hi, {name}!"
app.py:
Python
from utils import greet
print(greet("Sam"))
Run:
Bash
python app.py
What to look for:
Both files must be in the same folder, and you must run the script from that folder.
5) Import from a package (folders with modules)
Use this structure:
my_project/
app.py
my_package/
__init__.py
utils.py
my_package/utils.py:
Python
def slugify(text: str) -> str:
return text.strip().lower().replace(" ", "-")
app.py:
Python
from my_package.utils import slugify
print(slugify("Hello Imports"))
Run from the project root:
Bash
python app.py
What to look for:
Run python app.py from the root folder, not from inside my_package/.
Examples you can copy
1) Standard library import for file paths
Python
from pathlib import Path
path = Path("data") / "notes.txt"
print(path)
2) Third-party import and version check
Python
import requests
print(requests.__version__)
3) Cleaner imports with aliases
Python
import numpy as np
arr = np.array([1, 2, 3])
print(arr.mean())
Common mistakes and how to fix them
Mistake 1: Naming your file the same as the library
You create a file named random.py, then write:
Python
import random
print(random.randint(1, 10))
Why it breaks:
Python imports your local random.py instead of the real random library.
Correct approach:
- Rename your file to something else, like
random_demo.py. - Delete the
__pycache__/folder if it exists. - Run your script again.
Mistake 2: Installing a package but still getting ModuleNotFoundError
You run:
Bash
pip install requests
python app.py
Why it breaks:
pip might install into a different Python than the one running your script.
Correct approach:
Bash
python -m pip install requests
python app.py
Mistake 3: Using a relative import in a script and getting an error
Inside my_package/utils.py:
Python
from .helpers import clean
Then you run:
Bash
python my_package/utils.py
Why it breaks:
Relative imports need a package context. Running the file directly skips that context.
Correct approach:
Run from the project root:
Bash
python -m my_package
Or run a top-level script:
Bash
python app.py
Troubleshooting
If you see ModuleNotFoundError right after import x, run:
Bash
python -c "import sys; print(sys.executable)"
Then install with:
Bash
python -m pip install x
If you see ImportError: attempted relative import with no known parent package, stop running the module file directly. Run from the project root with:
Bash
python -m package_name
If an import works on your laptop but not another machine, create a requirements.txt file and install from it on both machines.
If your editor shows red underlines but the script runs, select the correct Python interpreter in the editor and restart it.
Quick recap
- Use
import mathfor built-in libraries. - Install third-party libraries with
python -m pip install package, thenimport package. - Use
from x import yorimport x as aliasfor cleaner code. - Import your own files with
from utils import funcwhen files share a folder. - Import packages with
from my_package.module import thingand run from the project root. - If imports fail, check the Python interpreter, current folder, and name conflicts.
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot