HOWTO · Python
How to Import a Variable From Another File in Python
This tutorial demonstrates how to import a variable from another file in Python. Learn various methods, including using the import statement, importing entire modules, and utilizing the importlib module for dynamic imports. Improve your Python coding skills with practical examples and clear explanations.
On this page
To use a variable defined in another Python file, import its module and then read the variable, or bind the name directly with from module import name. The module must be discoverable on Python’s import path. For a small project, keep both files in the same directory and run the importing script from that project.
Import a specific name with from ... import ...
Suppose config.py defines greeting = "Hello, World!". The importing file can use from config import greeting, then refer to greeting directly. The module name is the filename without .py. This form is convenient when you need only a few names. You can import several known names with a comma-separated list, such as from config import greeting, language.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
import sys
with TemporaryDirectory() as directory:
project = Path(directory)
(project / "config.py").write_text('greeting = "Hello, World!"\n', encoding="utf-8")
sys.path.insert(0, str(project))
from config import greeting
print(greeting)
This example is provided for the runtime coordinator to execute; no execution result was supplied with this writing packet.
Import the module and access its variable
Use import config and then read config.greeting when you want the source module to stay visible at each use. The module prefix makes the name’s origin clear and reduces collisions when different modules define names with the same spelling. Ordinary imports also bind the imported name when the import runs; changing a value later in the source module does not make a separately imported name a live link to it.
Import a module dynamically with importlib
Use importlib when the module name is selected at runtime, for example from a setting or a user choice. For a known module, a normal import is shorter and easier to follow. A self-contained dynamic form is:
from pathlib import Path
from tempfile import TemporaryDirectory
import importlib
import sys
with TemporaryDirectory() as directory:
project = Path(directory)
(project / "config.py").write_text('greeting = "Hello, World!"\n', encoding="utf-8")
sys.path.insert(0, str(project))
module_name = "config"
module = importlib.import_module(module_name)
print(module.greeting)
importlib.import_module() returns the module object, so access the variable through that object. The module still has to be discoverable through the import system.
Make a module in another directory importable
Python searches directories on its import path, not arbitrary files. A simple layout is project/main.py alongside project/settings/config.py; launch context and package setup determine whether settings.config can be imported. For a regular package, add __init__.py where appropriate and use the package name, such as from settings.config import greeting. Running from a different directory can change which locations Python searches, so prefer a consistent project launch method.
As a deliberate fallback for a standalone script, add the directory containing the module to sys.path before importing it. Resolve the directory from a stable location when possible rather than assuming the current working directory:
from pathlib import Path
from tempfile import TemporaryDirectory
import sys
with TemporaryDirectory() as directory:
project = Path(directory)
settings_directory = project / "settings"
settings_directory.mkdir()
(settings_directory / "config.py").write_text('greeting = "Hello, World!"\n', encoding="utf-8")
sys.path.insert(0, str(settings_directory))
from config import greeting
print(greeting)
This adds a directory to sys.path; it does not add the module file itself. For maintained applications, package imports or an installed package are usually easier to manage than changing the import path in application code.
Run and troubleshoot the examples
Save the module with the exact name used in the import, including matching letter case, and ensure the variable is defined at module level. If Python reports ModuleNotFoundError, check the filename, directory layout, how you launched the script, and whether the directory containing the module is on the import path. If Python reports ImportError for a name, verify that the spelling matches a name defined in the module. Avoid naming your own files after standard-library modules, since that can cause Python to load the wrong module.
A direct import is best for a fixed dependency. Choose from config import greeting for concise access to a small set of names, or import config when keeping the module namespace visible improves clarity. Use importlib when the module name genuinely depends on runtime data.