Importing Classes From Another File Python

7 min read

Importing classes from another file in Python is one of the most important skills a new programmer can learn when moving from small scripts to real applications. Instead of writing every class inside one long file, Python lets you organize your code into separate files, then reuse those classes wherever you need them. This improves readability, reduces repetition, and makes your projects easier to maintain. In this guide, you will learn how importing classes from another file Python works, why it matters, and how to avoid the most common mistakes beginners face Worth keeping that in mind..

Why Importing Classes From Another File Matters

When you start learning Python, it is common to put everything into a single file. You define variables, functions, and classes one after another. This works for tiny scripts, but it quickly becomes confusing as projects grow Not complicated — just consistent. Turns out it matters..

Splitting code into multiple files gives you several major benefits:

  • Better organization: Each file can focus on one responsibility.
  • Easier debugging: You can isolate problems to a specific file.
  • Reusable code: A class can be imported into many different scripts.
  • Improved collaboration: Teams can work on different files at the same time.
  • Cleaner projects: Your main file becomes easier to read.

To give you an idea, if you are building a small game, you might place player classes in player.py, enemy classes in enemy.On top of that, py, and item classes in items. py. Then your main file can import the classes it needs instead of containing hundreds of lines of code.

This changes depending on context. Keep that in mind.

How Python Turns Files Into Modules

Before importing a class, it helps to understand what Python does behind the scenes. This leads to in Python, every . py file can act as a module. A module is simply a file containing Python definitions and statements That alone is useful..

So if you have a file named shapes.py, Python sees that file as a module named shapes. Because of that, inside that module, you can define classes like Circle and Rectangle. Another file can then import those classes using the module name.

This is the core idea behind importing classes in Python: you are not magically reaching into another file. You are importing a module, then accessing one or more classes from that module Simple, but easy to overlook..

Basic Example: Importing a Class From Another File

Suppose you have two files in the same folder:

  1. shapes.py
  2. main.py

Inside shapes.py, you define a class:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

Now, inside main.py, you want to use the Circle class.

You can import it like this:

from shapes import Circle

circle = Circle(5)
print(circle.area())

When you run main.py, Python looks for a module named shapes, finds shapes.py, loads it, and gives you access to the Circle class.

We're talking about the simplest and most common way to import a class from another file in Python.

Step-by-Step Process for Importing Classes

The process is straightforward once you understand the structure Nothing fancy..

Step 1: Create the File That Contains the Class

Start by creating a Python file that defines the class. As an example, create vehicle.py:

class Car:
    def __init__(self, brand):
        self.brand = brand

    def describe(self):
        return f"This car is made by {self.brand}."

This file is now a module.

Step 2: Create the File That Will Use the Class

Next, create another file, such as main.py, in the same directory That's the part that actually makes a difference..

Step 3: Use the Import Statement

Inside main.py, write:

from vehicle import Car

my_car = Car("Toyota")
print(my_car.describe())

Step 4: Run the Main File

Run main.py. Python will load vehicle.py, locate the Car class, and allow your script to use it.

That is the entire basic workflow. The key thing to remember is that both files need to be in the same directory unless you are using more advanced import methods Practical, not theoretical..

Different Ways to Import a Class

There is more than one valid way to import a class. Each approach has slightly different syntax and use cases.

1. Import a Specific Class

Basically the cleanest method when you only need one or two classes:

from shapes import Circle

This makes the class available directly by its name.

2. Import Multiple Classes From the Same File

If a file contains several classes, you can import them together:

from shapes import Circle, Square

This keeps your code clear and avoids unnecessary imports.

3. Import the Entire Module

Instead of importing just one class, you can import the whole module:

import shapes

circle = shapes.Circle(5)

This approach is useful when you need many classes from the same file or when you want to keep the module name visible in your code Worth keeping that in mind..

4. Import a Module With an Alias

If a module name is long or conflicts with another name, you can create an alias:

import shapes as sh

circle = sh.Circle(5)

This is common in larger projects where names need to be shortened for convenience.

Importing Classes From a Package

As your project becomes more organized, you may place Python files inside folders. A folder that contains Python modules is often called a package.

Take this: your structure might look like this:

my_project/
    geometry/
        __init__.py
        shapes.py
    main.py

Inside geometry/shapes.py:

class Circle:
    def __init__(self, radius):
        self.radius

### Extending the Package Layout

When the project grows beyond a handful of files, grouping related modules into a package helps keep the codebase organized and makes imports clearer. A package is simply a directory that contains an `__init__.Even so, py` file (the file can be empty for Python 3. 3+).  

Below is a continuation of the earlier example, now expanded into a small package called **`geometry`**.

#### 1. Organize the files

my_project/ │ ├─ geometry/ │ ├─ init.py # makes geometry a package │ ├─ shapes.py # defines Circle, Square, etc. │ └─ utils.py # additional helper functions │ ├─ main.py # entry‑point script └─ README.md


#### 2. Define the classes inside `shapes.py`

```python
# geometry/shapes.py
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        import math
        return math.pi * self.radius ** 2

class Square:
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

3. Expose the classes through the package’s public API

geometry/__init__.py can re‑export the most useful symbols so that users of the package don’t need to know the internal file layout.

# geometry/__init__.py
from .shapes import Circle, Square

# Optionally import utilities as well
from . import utils

Now the package itself acts as a single import target Turns out it matters..

4. Importing from the package

Inside main.py you can pull the classes directly from the package:

# main.py
from geometry import Circle, Square

circle = Circle(3)
square = Square(4)

print(f"Circle area: {circle.area():.2f}")
print(f"Square area: {square.area()}")

If you prefer to import the whole module and reference the classes with a dot, that works too:

import geometry.shapes as gs

c = gs.Circle(5)
print(c.area())

5. Relative imports for internal modules

When a module needs to import something from another file within the same package, using a relative import keeps the code resilient to renaming or moving the package.

# geometry/utils.py
from .shapes import Circle

def describe(circle: Circle) -> str:
    return f"The circle’s radius is {circle.radius}."

Notice the leading dot before shapes; it tells Python to resolve the name relative to the current package rather than the global namespace Worth knowing..

6. Handling deeper sub‑packages

If the hierarchy becomes more complex, you can nest packages:

my_project/
    geometry/
        __init__.py
        shapes/
            __init__.py
            circle.py
            square.py
        utils.py

geometry/shapes/__init__.py might expose the sub‑modules:

# geometry/shapes/__init__.py
from .circle import Circle
from .square import Square

__all__ = ['Circle', 'Square']

Now from geometry.shapes import Circle, Square works, and each sub‑module can keep its own implementation details separate.

7. Best‑practice checklist

  • Keep __init__.py minimal – only re‑export symbols that are part of the public API; avoid importing heavy modules at package load time.
  • Prefer explicit imports – from geometry.shapes import Circle is clearer than import geometry.shapes when you need just one class.
  • Watch out for circular dependencies – if two modules import each other, consider moving the shared code to a third module or using lazy imports (import importlib; module = importlib.import_module('...')).
  • Document the public surface – the __all__ list in an __init__.py helps tools like help() and IDE auto‑completion.

Conclusion

Importing a class in Python is straightforward when the class lives in a single file, but the real power emerges as projects scale. That said, by arranging modules into packages, exposing a clean public interface via __init__. py, and employing relative imports, you maintain readability, avoid name clashes, and make your codebase easier to work through. Following these patterns ensures that your Python applications remain modular, maintainable, and ready for future expansion.

Fresh from the Desk

Fresh Stories

Neighboring Topics

Also Worth Your Time

Thank you for reading about Importing Classes From Another File Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home