Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 49 of 70

Python modules and the import statement

Split Python code into modules, load them with import, from and as, understand the __name__ guard, and see how Python finds the files, with real output.

14 minModules and packagesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate your own module, import it in three different ways, and use the __name__ guard so a file works both as a script and as a module.

After this lesson you can move code into its own file, import it from another file, and write modules that are safe to both run and import.

Why modules

As a program grows, one file becomes hard to read. A module is just a Python file. By moving related functions into their own files you get smaller, named pieces that can be reused in several programs. The standard library is a large collection of such modules, and the next lessons cover it.

Your first module

Here is a small module for a shop. Save this as shop_utils.py:

python
#file: shop_utils.py
TAX_RATE = 0.18

def add_tax(amount):
    return round(amount * (1 + TAX_RATE), 2)

def format_price(amount):
    return f"Rs {amount:,.2f}"

In the same folder, you can now use it from another file, or from the interactive prompt, with import:

python
import shop_utils

print(shop_utils.TAX_RATE)
print(shop_utils.add_tax(100))
print(shop_utils.format_price(1234.5))
result
0.18
118.0
Rs 1,234.50

After a plain import, the module's names are kept inside the module object, so you reach them with a dot. This keeps your program tidy: you can always see where a function came from.

Importing specific names

If you use one function often, bring it in directly with from ... import:

python
from shop_utils import add_tax, format_price

print(format_price(add_tax(250)))
result
Rs 295.00

Now the names are used without the prefix. The trade-off is that the origin is less obvious when a file grows. A third form renames what you import:

python
import shop_utils as su
from shop_utils import TAX_RATE as rate

print(su.add_tax(200))
print(rate)
result
236.0
0.18

Aliases are mostly used for long module names. There is also from shop_utils import *, which pulls in everything. Avoid it, because you can no longer tell where a name came from, and it may silently overwrite your own names.

What import really does

The first time Python sees import something, it finds the file, runs it from top to bottom, and stores the resulting module object. You can prove that the file runs with a module that prints something:

python
#file: noisy.py
print("noisy.py is being loaded")
VALUE = 42
python
import noisy
import noisy
print(noisy.VALUE)
result
noisy.py is being loaded
42

The message appears once, even though the module was imported twice. Python keeps a cache of loaded modules and reuses it. This also means top-level code in a module should be quick and free of surprises.

The name guard

Every module has a built-in variable called __name__. When the file is imported, it holds the module's name. When the file is run directly, it holds the string "__main__". That lets one file act as both a library and a program.

python
#file: price_tool.py
def double(amount):
    return amount * 2

if __name__ == "__main__":
    print("running directly")
    print(double(21))

Run it directly from a terminal:

bash
python3 price_tool.py
result
running directly
42

Now import it instead:

python
import price_tool

print(price_tool.__name__)
print(price_tool.double(5))
result
price_tool
10

The test code inside the if block did not run on import. Without the guard, simply importing the module would have printed the test lines every time. Put demonstrations and the program's entry point under the guard.

How Python finds a module

When you write import shop_utils, Python looks through a list of folders called sys.path, in order. The first entry is the folder of the script you ran, followed by the standard library and installed packages. If no file matches, you get an error:

python
import shop_utilz
result
ModuleNotFoundError: No module named 'shop_utilz'

Two practical consequences follow. First, keep your modules next to your script or in a package (see the lesson on packages). Second, never name your own file after a standard module. A file called random.py or json.py in your folder would be found first, and import random would load your file instead of the real one.

Looking inside a module

The built-in dir() lists the names a module defines, and help() shows docstrings. You can filter out the internal double-underscore names:

python
print([name for name in dir(shop_utils) if not name.startswith("__")])
result
['TAX_RATE', 'add_tax', 'format_price']

Modules can hold anything

A module is not limited to functions. It can hold constants, classes and data, and Python treats a variable defined in a module as shared by everyone who imports it. That makes a module a convenient place for settings:

python
#file: settings.py
SHOP_NAME = "Corner Shop"
OPENING_HOURS = (9, 18)
python
import settings

print(settings.SHOP_NAME)
print(settings.OPENING_HOURS)
result
Corner Shop
(9, 18)

Because the module is cached, every file that imports settings sees the same values. Keep such modules small and plain. Putting a lot of logic into a settings file makes it hard to understand what happens at import time.

Common mistakes

  • Saving the module under a name that clashes with a standard module, such as random.py or email.py.
  • Forgetting the module prefix after a plain import. Writing add_tax(100) after import shop_utils raises a NameError.
  • Importing from a different folder than you expected. The folder you start Python in matters.
  • Editing a module and not seeing the change in an open interactive session. The module is cached, so restart Python.
  • Using from x import * in real code.
  • Putting a hyphen in a module name. A file called shop-utils.py cannot be imported with a normal import. Use underscores.

Exercise

Create a module greetings.py with a function welcome(name) that returns "Welcome, <name>!". Add a __name__ guard that prints the welcome for "Test" only when the file is run directly. Then import the function from another file.

Show one possible answer
python
#file: greetings.py
def welcome(name):
    return f"Welcome, {name}!"

if __name__ == "__main__":
    print(welcome("Test"))
python
from greetings import welcome

print(welcome("Asha"))
result
Welcome, Asha!

Key points

  • A module is simply a .py file. Importing it runs the file once and gives you access to its names.
  • import shop_utils keeps names behind the module name. from shop_utils import add_tax brings a name in directly. import ... as gives a shorter alias.
  • Python caches imported modules, so a second import does not run the file again.
  • Python searches the folder of the running script, then the installed packages, so a module name must not clash with a standard one.
  • Wrap script-only code in if __name__ == '__main__': so that importing the file does not run it.

Check yourself

1. What is a module in Python?
2. After import shop_utils, how do you call its add_tax function?
3. What is the value of __name__ inside a file run directly as python3 file.py?
4. You import the same module twice in one program. How many times does its top-level code run?