import and from import do the same thing in different shapes: both load a module into your program, but import module gives you the module name to reach into, while from module import name copies just the names you ask for into the current file. Use plain import when you want clarity about where a function came from and from module import name when you call a few items often and want shorter code. You need Python installed and a text editor; nothing else. The examples below use only the standard library, so they run on any recent Python 3 install.
What You'll Need
- Python 3 installed and working from a terminal (check with
python3 --version, orpython --versionon Windows). - A text editor or IDE to write
.pyfiles. Avoid notebook cells at first: import behaviour is easier to see in a plain script. - A folder for practice files. Import rules depend on where files sit, so keep it simple and empty except for your own scripts.
- Basic comfort running a script from the command line, e.g.
python3 hello.py.
Step-by-Step
- Start with a plain import and use the dotted name. Create
main.pyand writeimport mathon the first line, thenprint(math.sqrt(144)). Run it. You get 12.0. The module objectmathis now a name in your file, and everything inside it is reached with a dot. This is the safest habit because a reader can always see thatsqrtcame frommath. - Import from a package's submodule. Many useful things live deeper than the top level. Write
import os.pathand thenprint(os.path.join("data", "file.txt")). Notice you still type the fullos.pathchain. If you write onlyimport os, thenos.pathmay not be available until something else loads it, so import the full path you intend to use. - Switch to
fromimport for individual names. Rewrite the file asfrom math import sqrtfollowed byprint(sqrt(144)). No prefix is needed;sqrtis now a normal name in your script. This is the form you will see most often for libraries such asfrom pathlib import Path. - Import several names at once, or all of them.
from math import sqrt, floor, ceilis fine and readable.from math import *also works but is hard to audit: you cannot tell which names came from where, and it can silently overwrite your own variables. Avoid it in real code. - Rename a name when it clashes or is long. Write
import datetime as dtand thenprint(dt.date.today()). Theasform works withfromtoo:from collections import OrderedDict as OD. Aliasing is the standard fix when two libraries export the same name. - Import your own module from a file in the same folder. Make
helpers.pycontainingdef greet(name): return "Hello " + name. Inmain.pyputimport helpersand callhelpers.greet("Sam"), or usefrom helpers import greet. Runpython3 main.pyfrom inside that folder. Python finds the module because the script's own directory is on the search path. - Learn the one thing
fromimport cannot do.from helpers import greetcopies the function object, not a live link to the module. If you later monkey-patchhelpers.greet, your imported name still points at the original. When you need to see later changes to the module's attributes, keep the module object withimport helpers. - Use absolute imports inside a package. If you make a folder
app/with__init__.pyand two modules, writefrom app.utils import cleanrather than a bareimport utils. Absolute imports are unambiguous and easier to move. Relative imports such asfrom .utils import cleanwork only when the file is run as part of the package, not as a standalone script. - Run modules safely with the main guard. Add
if __name__ == "__main__":above any code that should only run when a file is executed directly. It stops test code from firing when the module is imported elsewhere.
Common Mistakes
Naming a file after a standard library module. If you create random.py or email.py in your folder, import random may load your file instead of the real one, and you get confusing AttributeError messages. Rename your file.
Importing a module and calling a function without the prefix. import math then sqrt(4) fails with NameError, because only math was added to the namespace. Either call math.sqrt or change to from math import sqrt.
Importing a package when you meant a function. from math import math makes no sense; math is the module, not something inside itself. Reading the docs' example lines usually settles this.
Using a module before importing it, or importing inside a function by accident. Imports at the top are easier to scan and run once. Imports buried in functions run every call and hide dependencies.
Running a package file directly and expecting relative imports to work. python3 app/utils.py breaks from .helpers import x. Run the package with python3 -m app.main instead, or switch to absolute imports.
Circular imports. Two modules importing each other at the top level can produce ImportError or half-built modules. Move the shared code into a third module, or import inside the function that needs it.
Tips
- Prefer
import modulewhen the module name is short and the code is long:os.pathis clearer than a crowd of bare names. - Prefer
from module import namefor heavily used classes likePathordatetime; prefixing every line adds noise. - Keep imports grouped at the top: standard library first, then third-party packages, then your own modules, each group separated by a blank line.
- Import order does not just look tidy. A module runs top-level code the first time it is imported, and Python caches it in
sys.modules, so a later import is cheap but will not re-run that code. - Avoid
from module import *in anything you plan to share or maintain.
Troubleshooting
ModuleNotFoundError for a file you can see. Check three things in order. First, confirm you are running the script from the folder that holds it. Second, print the working directory and the search path with import sys; print(sys.path). Third, check the file name is spelled exactly and ends in .py. The first entry in sys.path is the script's folder, so running from the wrong place is the usual culprit.
ImportError: cannot import name X. Either X is spelled differently, or it lives in a submodule. For example, from os import path works but a name inside path must be imported from os.path. Check the official docs for the exact location.
Stale behaviour after editing a module. Python caches compiled bytecode and keeps modules in memory. In a long-running session, restart the interpreter. For notebooks or interactive shells, a full restart is the reliable fix.
Something works in the terminal but not in your editor. The editor may be using a different interpreter or a different working directory. Point it at the same Python you tested with and open the project folder as the root.
Still failing? Cut a minimal script with one import and one print, run it, then add pieces back. That isolates whether the problem is the import itself or the code around it.
Frequently Asked Questions
Is from x import y faster than import x?
Not meaningfully. Both load the module once. The only time it matters is binding many names, which is negligible against real work.
Can I import a module only when a function runs?
Yes. Putting an import inside a function defers the load until the first call. This is legitimate for optional dependencies or to break a circular import, but imports at the top are easier to read.
What does if __name__ == "__main__" actually check?
It checks whether the file is the program's entry point. Run directly, __name__ is "__main__"; imported from elsewhere, it is the module's name.
Why does import * hide names?
It dumps everything public into your namespace. You cannot see where a name came from, and it can overwrite your own variables without warning.
Do imports run every time they appear in the file?
They are executed each time the statement runs, but the module's code runs only on the first import in that process. Later imports reuse the cached module.