Skip to main content
Editor

Python Imports: How import Really Works (Modules, Packages, Paths)

Beginner20 min5 exercises55 XP
0/5 exercises

Think of a library. Instead of buying every book in the world and keeping them in your house, you go to the library and check out only the books you need. When you're done, you return them.

Python's import system works the same way. Python comes with hundreds of built-in modules - collections of useful code that other people have already written. Instead of writing everything from scratch, you import just the tools you need.

In this tutorial, you'll learn the different ways to import code in Python, how to rename imports for convenience, what __name__ == '__main__' means, and how Python finds the modules you ask for.

What Is the Difference Between import and from...import?

There are two main ways to bring code into your program. The first is import, which brings in an entire module. The second is from...import, which grabs just the specific pieces you want.

Let's start with the basic import statement. When you write import math, Python loads the entire math module. To use anything from it, you prefix it with the module name.

Using import with the module name
import math
print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7))
Output
4.0
3.141592653589793
3

Notice you always write math.sqrt(), not just sqrt(). The module name acts like a label that keeps things organized. It's like saying "the sqrt function from the math module."

Now compare that to from...import. This pulls specific names directly into your code, so you can use them without the module prefix.

Using from...import
from math import sqrt, pi
print(sqrt(16))
print(pi)
# print(math.floor(3.7)) # This would cause an error!
Output
4.0
3.141592653589793

With from math import sqrt, pi, you get sqrt and pi directly - no prefix needed. But you don't get floor or anything else you didn't import. And math itself isn't available as a name.

import math
import math

math.sqrt(16)    # Must use prefix
math.pi          # Must use prefix
# Everything in math is available
from math import sqrt, pi
from math import sqrt, pi

sqrt(16)    # No prefix needed
pi          # No prefix needed
# Only sqrt and pi are available

How Do You Import Specific Names from a Module?

You can import one name, several names, or (in rare cases) everything from a module. Let's look at each option.

Importing one or many names
# Import one thing
from random import randint
print('Random number:', randint(1, 10))
# Import multiple things
from math import sqrt, ceil, floor
print('sqrt(25) =', sqrt(25))
print('ceil(3.2) =', ceil(3.2))
print('floor(3.8) =', floor(3.8))
Output
Random number: 2
sqrt(25) = 5.0
ceil(3.2) = 4
floor(3.8) = 3

You might see code that uses from module import *. This imports everything from the module at once. It seems convenient, but it's almost always a bad idea.

Why import * is dangerous
# DON'T do this in real code!
# from math import *
# from random import *
# Now sqrt could come from math or random - confusing!
# DO this instead - be explicit
from math import sqrt
from random import randint
print('sqrt(9) =', sqrt(9))
print('randint(1, 5) =', randint(1, 5))
Output
sqrt(9) = 3.0
randint(1, 5) = 1

How Do You Rename Imports with as?

Sometimes module names are long or you want a shorter nickname. The as keyword lets you create an alias - a shorter name for the module or function.

Module alias with as
# Give a module a shorter name
import math as m
print(m.sqrt(100))
print(m.pi)
print(m.ceil(4.3))
Output
10.0
3.141592653589793
5

After import math as m, you use m.sqrt() instead of math.sqrt(). The original name math is no longer available - only the alias m works.

You can also alias individual imports from from...import.

Aliasing specific imports
from datetime import datetime as dt
from collections import Counter as C
now = dt.now()
print('Current time:', now.strftime('%H:%M:%S'))
word_counts = C(['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'])
print('Counts:', dict(word_counts))
Output
Current time: 11:58:38
Counts: {'apple': 3, 'banana': 2, 'cherry': 1}

What Does __name__ == '__main__' Mean?

Every Python file has a special variable called __name__. When you run a file directly, Python sets __name__ to the string '__main__'. When you import that file from somewhere else, __name__ gets set to the module's name instead.

Checking __name__
# When you run a file directly:
print('__name__ is:', __name__)
Output
__name__ is: __main__

This is useful because it lets you write code that behaves differently depending on whether it's being run directly or imported as a module.

The if __name__ guard
def greet(name):
return f'Hello, {name}!'
def add(a, b):
return a + b
# This block only runs when the file is executed directly,
# not when it's imported by another file
if __name__ == '__main__':
print(greet('Alice'))
print(f'2 + 3 = {add(2, 3)}')
print('Running as main program!')
Output
Hello, Alice!
2 + 3 = 5
Running as main program!

Think of it like this: the if __name__ == '__main__' block is the front door of your program. If someone runs your file directly, they come through the front door and see the demo. If another file imports your code, they go through the side door and only get the functions - no demo runs.

How Does Python Find the Modules You Import?

When you write import math, Python doesn't magically know where math lives. It searches through a list of directories in a specific order. This list is stored in sys.path.

Viewing sys.path
import sys
print('Python searches these locations for modules:\n')
for i, path in enumerate(sys.path[:5]):
print(f' {i + 1}. {path}')
if len(sys.path) > 5:
print(f' ... and {len(sys.path) - 5} more locations')
Output
Python searches these locations for modules:

  1. 
  2. /lib/python313.zip
  3. /lib/python3.13
  4. /lib/python3.13/lib-dynload
  5. /lib/python3.13/site-packages

Python checks these locations in order:

  • The current directory (where your script lives)
  • Directories in PYTHONPATH (an environment variable you can set)
  • The standard library (built-in modules like math, os, json)
  • Installed packages (third-party libraries you've installed)
  • If Python searches every location and can't find the module, you get a ModuleNotFoundError.

    What happens when a module is not found
    try:
    import this_module_does_not_exist
    except ModuleNotFoundError as e:
    print(f'Error: {e}')
    print('Python looked everywhere but couldn\'t find it!')
    Output
    Error: No module named 'this_module_does_not_exist'
    Python looked everywhere but couldn't find it!

    You can also check where a module is located after importing it using the __file__ attribute (when available).

    Inspecting modules
    import json
    import collections
    # Some modules show their file location
    print('json module:', type(json))
    print('collections module:', type(collections))
    # You can list everything in a module
    print('\nThings in json module:')
    print([x for x in dir(json) if not x.startswith('_')])
    Output
    json module: <class 'module'>
    collections module: <class 'module'>
    
    Things in json module:
    ['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

    How Do Real Python Programs Use Imports?

    In real Python projects, imports always go at the top of the file. There's a standard ordering convention that keeps things tidy.

    Conventional import ordering
    # 1. Standard library imports (built into Python)
    import os
    import json
    from datetime import datetime
    from collections import defaultdict
    # 2. Third-party imports (installed with pip)
    # import requests
    # import numpy as np
    # 3. Your own project imports
    # from myapp.utils import helper
    # Now use them
    data = {'name': 'Alice', 'scores': [95, 87, 92]}
    json_string = json.dumps(data, indent=2)
    print(json_string)
    counts = defaultdict(int)
    for char in 'hello world':
    counts[char] += 1
    print('\nCharacter counts:', dict(counts))
    Output
    {
      "name": "Alice",
      "scores": [
        95,
        87,
        92
      ]
    }
    
    Character counts: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

    Practice Exercises

    Predict the Output: import vs from...import
    Predict Output

    What will this code print?

    from math import sqrt, pow
    
    a = sqrt(49)
    b = pow(2, 3)
    print(a)
    print(b)

    Remember that math.pow() returns a float.

    # Type the exact output
    Use the random Module
    Write Code

    Import the random module and use random.seed(42) to make results predictable. Then:

    1. Use random.randint(1, 100) to generate a random number and print it

    2. Create a list colors = ['red', 'blue', 'green', 'yellow']

    3. Use random.choice(colors) to pick a random color and print it

    The seed ensures the same "random" numbers every time.

    # Import random and set seed to 42
    Fix the Bug: Broken Imports
    Fix the Bug

    This code has import errors. Fix all the problems so it runs correctly and produces the expected output.

    Expected output:

    4.0
    3.141592653589793
    5
    from math import sqrt
    from math import pi
    print(sqrt(16))
    print(pi)
    print(math.gcd(10, 15))
    Use Import Aliases
    Write Code

    Import the datetime module with the alias dt. Then:

    1. Create a date object for January 15, 2025 using dt.date(2025, 1, 15) and store it in my_date

    2. Print the date using print(my_date)

    3. Print the year using print(my_date.year)

    4. Print the weekday name using print(my_date.strftime('%A'))

    # Import datetime with an alias
    Write a Module with __name__ Guard
    Write Code

    Write a small "module" that:

    1. Defines a function celsius_to_fahrenheit(c) that returns c * 9/5 + 32

    2. Defines a function fahrenheit_to_celsius(f) that returns (f - 32) * 5/9

    3. Has an if __name__ == '__main__' guard that:

    - Prints 'Running temperature converter'

    - Prints celsius_to_fahrenheit(0)

    - Prints celsius_to_fahrenheit(100)

    - Prints fahrenheit_to_celsius(212)

    # Define the functions and the __name__ guard

    Related Tutorials

    Was this tutorial helpful?