Importing variables from another file?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
In another file you can access those variables through the module name:
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:
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:
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:
Inside database/connection.py:
You can import from it in main.py like this:
If you want to expose certain names at the package level, re-export them in __init__.py:
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":
Two dots mean "the parent package":
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:
Three strategies to fix this:
1. Move the import inside the function:
2. Restructure so shared definitions live in a third file that both A and B import from.
3. Import the module, not the name:
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.pyin your project,import randomwill load your file instead of the standard library module. - Running a package file directly: Executing
python database/models.pybreaks relative imports. Usepython -m database.modelsinstead. - 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 DEBUGcopies the reference. ReassigningDEBUG = Falsein the importing file does not changeconfig.DEBUG. Import the module and mutateconfig.DEBUGif you need shared state. - Forgetting
__init__.py: In Python 3 namespace packages can work without__init__.py, but explicit__init__.pyfiles make package boundaries clear and let you control what gets exported.
Summary
- Use
import modulefor full-module access andfrom module import namefor specific variables. - Alias imports with
asto avoid name collisions. - Create packages with
__init__.pyand 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
- ImproperlyConfiguredError about app_name when using namespace in include
- Improve subplot size/spacing with many subplots
- Impute entire DataFrame all columns using Scikit-learn sklearn without iterating over columns
- In Flask convert form POST object into a representation suitable for mongodb
- In Javascript / ES6, how do I wait for Python code to finish executing in a Jupyter Notebook?
- In MongoDB''s pymongo, how do I do a count?
- In pandas, is inplace True considered harmful, or not?
- In practice, what are the main uses for the yield from syntax in Python 3.3?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.