Python
Code
Import
Programming
Software Development

Importing class from another file

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Importing a class from another file in Python is straightforward when your project structure and execution method are consistent. Most import problems come from running files directly from the wrong location, not from Python syntax itself. A package-first layout with absolute imports is the most reliable approach for applications and reusable libraries.

Project Layout That Supports Clean Imports

Use a package directory with __init__.py files so Python treats folders as importable modules.

text
1myapp/
2  pyproject.toml
3  src/
4    myapp/
5      __init__.py
6      models.py
7      services.py
8      main.py

Define your class in one file and import it from another.

python
1# src/myapp/models.py
2class User:
3    def __init__(self, user_id: int, email: str):
4        self.user_id = user_id
5        self.email = email
python
1# src/myapp/services.py
2from myapp.models import User
3
4
5def create_demo_user() -> User:
6    return User(1, "[email protected]")

This absolute-import style remains stable as the codebase grows.

Run Modules Correctly

How you start Python determines import resolution behavior. From the project root, run modules with -m so package context is preserved.

bash
python -m myapp.main

If you run a file directly by path, imports that work in package mode may fail.

bash
# Often problematic in package projects
python src/myapp/main.py

A minimal entry point might look like this:

python
1# src/myapp/main.py
2from myapp.services import create_demo_user
3
4
5def main() -> None:
6    user = create_demo_user()
7    print(user.user_id, user.email)
8
9
10if __name__ == "__main__":
11    main()

Relative Imports Inside a Package

Relative imports can be useful for closely related modules, but they must run inside package context.

python
# src/myapp/services.py
from .models import User

Both absolute and relative styles are valid. Teams usually pick one convention to keep reviews consistent.

Avoid sys.path Hacks

You can mutate sys.path to force imports, but this hides packaging problems and makes behavior environment-dependent.

python
# Avoid in normal application code
import sys
sys.path.append('/some/path')

Prefer one of these instead:

  • Install the project in editable mode with pip install -e .
  • Run modules with python -m package.module
  • Keep source under a package directory and test from project root

These patterns make IDE, test runner, and production behavior consistent.

Debugging Import Errors Quickly

When an import fails, print runtime clues.

python
import sys
print('python executable:', sys.executable)
print('first path entry:', sys.path[0])

Then confirm the package is installed or discoverable from the current working directory. In virtual environments, verify the active interpreter is the one where dependencies and your package are installed.

Keep Imports Stable in Tests and Tooling

Test runners and task tools may change working directory behavior. Add a simple smoke test that imports your package exactly the way production code does. This catches path drift early.

python
1# tests/test_imports.py
2from myapp.models import User
3
4
5def test_user_imports() -> None:
6    u = User(7, "[email protected]")
7    assert u.user_id == 7

Run tests from project root in CI so local and remote import resolution rules stay aligned.

Common Pitfalls

  • Running module files directly instead of using package execution with -m.
  • Missing __init__.py files in package directories.
  • Mixing absolute and relative imports without a team convention.
  • Fixing errors with sys.path mutation instead of proper packaging.
  • Using one interpreter in terminal and another in IDE, causing inconsistent import behavior.

Summary

  • Organize code as a package and prefer absolute imports for long-term clarity.
  • Execute entry points with python -m from project root.
  • Use relative imports only within clear package boundaries.
  • Avoid sys.path workarounds that mask structural issues.
  • Validate interpreter and module path settings when debugging import failures.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.