Python
Import Variables
File Handling
Programming
Code Integration

Importing variables 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

Splitting code across multiple files is one of the first things you do as a Python project grows. Python's import system lets you pull variables, functions, and classes from one file into another so you can keep each file focused on a single responsibility. This article covers every common import pattern, from the basic import statement through relative imports and __init__.py, with runnable examples for each.

Basic Import

The simplest approach is to import an entire module by name. Suppose you have a file called config.py:

python
1# config.py
2DATABASE_HOST = "localhost"
3DATABASE_PORT = 5432
4DEBUG = True

In another file you can access those variables through the module name:

python
1# app.py
2import config
3
4print(config.DATABASE_HOST)  # "localhost"
5print(config.DATABASE_PORT)  # 5432

Python executes config.py once when you first import it, and every subsequent import config in other files reuses the same module object. The variables are accessed as attributes of the module.

Importing Specific Variables with from ... import

When you only need a few names, pull them in directly:

python
1# app.py
2from config import DATABASE_HOST, DEBUG
3
4print(DATABASE_HOST)  # "localhost"
5print(DEBUG)          # True

This style is convenient because you avoid repeating the module name, but it also means the imported names live directly in the current namespace. If two modules define a variable with the same name, the second import silently overwrites the first.

Aliased Imports

You can rename an import to avoid name collisions or to shorten a long module name:

python
from config import DATABASE_HOST as DB_HOST

print(DB_HOST)  # "localhost"

This is common with libraries like NumPy (import numpy as np) and keeps the rest of your code concise.

Packages and __init__.py

When your project has subdirectories, Python treats each directory as a package if it contains an __init__.py file (which can be empty). Consider this layout:

 
1project/
2    main.py
3    database/
4        __init__.py
5        connection.py
6        models.py

Inside database/connection.py:

python
# database/connection.py
CONNECTION_STRING = "postgresql://localhost/mydb"

You can import from it in main.py like this:

python
1# main.py
2from database.connection import CONNECTION_STRING
3
4print(CONNECTION_STRING)

If you want to expose certain names at the package level, re-export them in __init__.py:

python
# database/__init__.py
from .connection import CONNECTION_STRING
from .models import User

Now callers can write from database import CONNECTION_STRING without knowing which internal file defines it.

Relative Imports

Inside a package, you can use dots to refer to sibling or parent modules. A single dot means "the current package":

python
1# database/models.py
2from .connection import CONNECTION_STRING
3
4class User:
5    db = CONNECTION_STRING

Two dots mean "the parent package":

python
# database/utils/helpers.py
from ..connection import CONNECTION_STRING

Relative imports only work inside packages (directories with __init__.py). They will raise an ImportError if you try to run the file directly as a script.

Avoiding Circular Imports

Circular imports happen when module A imports module B and module B imports module A. Python will raise an ImportError or give you partially initialized modules. Here is a typical example of the problem:

python
1# a.py
2from b import helper_b
3VALUE_A = 10
4
5# b.py
6from a import VALUE_A      # fails -- a.py has not finished loading yet
7def helper_b():
8    return VALUE_A + 1

Three strategies to fix this:

1. Move the import inside the function:

python
1# b.py
2def helper_b():
3    from a import VALUE_A  # imported at call time, not at load time
4    return VALUE_A + 1

2. Restructure so shared definitions live in a third file that both A and B import from.

3. Import the module, not the name:

python
1# b.py
2import a
3
4def helper_b():
5    return a.VALUE_A + 1

This works because by the time helper_b runs, module a is fully initialized.

Common Pitfalls

  • Shadowing module names with file names: If you create a file called random.py in your project, import random will load your file instead of the standard library module.
  • Running a package file directly: Executing python database/models.py breaks relative imports. Use python -m database.models instead.
  • Circular imports at the top level: Two files importing from each other at module scope causes partially loaded modules. Move one import inside a function or extract shared code.
  • Mutating imported variables: from config import DEBUG copies the reference. Reassigning DEBUG = False in the importing file does not change config.DEBUG. Import the module and mutate config.DEBUG if you need shared state.
  • Forgetting __init__.py: In Python 3 namespace packages can work without __init__.py, but explicit __init__.py files make package boundaries clear and let you control what gets exported.

Summary

  • Use import module for full-module access and from module import name for specific variables.
  • Alias imports with as to avoid name collisions.
  • Create packages with __init__.py and use re-exports to build clean public APIs.
  • Relative imports (. and ..) work inside packages for referencing sibling modules.
  • Break circular imports by deferring the import into a function body, extracting shared code, or importing the module object instead of individual names.

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.