To import constants from another file in Python, you create a separate Python file (e.g., constants.py) to hold your variables and then use the import or from ... import statement in your main script. This allows you to centralize configuration values, API keys, and fixed parameters, making your code easier to maintain and preventing duplication across multiple modules.
What You'll Need
- Python installed on your system (Python 3.x is recommended).
- A code editor or IDE (such as VS Code, PyCharm, or a basic text editor).
- Two or more Python files located within the same project directory.
Step-by-Step
- Create your constants file: Create a new file named
constants.py. In Python, constants are typically written in ALL_CAPS to signal to other developers that these values should not be changed during the program's execution. For example, add the following lines toconstants.py:# constants.py API_KEY = "12345-ABCDE" DATABASE_URL = "localhost:5432" TIMEOUT_SECONDS = 30 MAX_RETRIES = 5 VERSION = "1.0.2" - Create your main application file: Create a second file in the same folder, such as
main.py. This is where you will utilize the values defined in the constants file. - Choose your import method: Depending on how you want to access the data, you have three primary ways to import these constants.
- Method A: Import the entire module. Use
import constantsat the top ofmain.py. This keeps your namespace clean because every constant must be prefixed with the module name.# main.py import constants print(constants.API_KEY) print(constants.TIMEOUT_SECONDS)This method is ideal for large projects where you might have multiple files with similar variable names; it makes it clear exactly which file the constant is coming from. - Method B: Import specific constants. Use
from constants import API_KEY, TIMEOUT_SECONDS. This allows you to use the variable names directly without theconstants.prefix.# main.py from constants import API_KEY, TIMEOUT_SECONDS print(API_KEY) print(TIMEOUT_SECONDS)This is the most common approach when you only need a few specific values and want to keep the code concise. - Method C: Import everything with a wildcard. Use
from constants import *. This imports every variable defined inconstants.pyinto your current namespace.# main.py from constants import * print(DATABASE_URL) print(MAX_RETRIES)While convenient for very small scripts, this is generally discouraged in professional development because it can lead to "namespace pollution," where you accidentally overwrite a local variable with an imported constant. - Run your program: Execute your main script using the command
python main.py. Python will look forconstants.pyin the current directory, load the values into memory, and print them to the console.
Common Mistakes
One of the most frequent errors is naming the constants file something that conflicts with a built-in Python library. For example, if you name your file random.py or json.py, Python may try to import your file instead of the standard library, leading to AttributeError or ImportError. Always use unique, descriptive names for your configuration files.
Another common mistake is placing the constants file in a different folder without telling Python how to find it. By default, Python looks in the directory of the script being executed. If your constants are in a folder named config/, simply calling import constants will fail. You would instead need to use from config import constants, provided the folder contains an __init__.py file (required for older Python versions) or is recognized as a namespace package.
Developers also frequently forget that Python does not have a strict const keyword like JavaScript or C++. The ALL_CAPS naming convention is a social contract among programmers, not a technical restriction. If you write constants.API_KEY = "new_value" in your main script, Python will allow it. To prevent this, some developers use a NamedTuple or a frozen dataclass to create truly immutable constants.
Tips
For better organization in larger projects, group your constants into categories. Instead of one giant constants.py, you might have db_constants.py, api_constants.py, and ui_constants.py. This reduces the amount of data loaded into memory if a specific module only needs a small subset of configurations.
If your constants include sensitive information like passwords or secret API keys, do not store them in a plain .py file that gets committed to version control (like GitHub). Instead, use a .env file and the python-dotenv library. You can then import these environment variables into a constants file, keeping your secrets safe while still maintaining a central point of access in your code.
Consider using a dictionary for constants that are logically related. For example, instead of COLOR_RED = "#FF0000" and COLOR_BLUE = "#0000FF", you could use a dictionary: COLORS = {"red": "#FF0000", "blue": "#0000FF"}. This allows you to iterate over the constants or access them dynamically using a key.
Troubleshooting
If you encounter a ModuleNotFoundError: No module named 'constants', first verify that the file name is exactly constants.py and that it is located in the same directory as the script you are running. Check for typos in the filename and the import statement.
If you receive an ImportError or AttributeError stating that the module has no attribute 'VARIABLE_NAME', ensure you have saved the constants.py file after adding the new variable. A common issue in IDEs is running the code while the constants file remains unsaved on the disk.
If you are importing from a subfolder and it is not working, ensure your directory structure is correct. For a folder named settings containing constants.py, your import should be from settings import constants. If this still fails, try adding an empty file named __init__.py inside the settings folder to explicitly mark it as a Python package.
In cases where you have circular imports (e.g., constants.py imports from main.py while main.py imports from constants.py), Python will throw an error. The solution is to ensure that the constants file remains "leaf-level," meaning it should never import from the logic files that depend on it. Constants should be independent of the application logic.
Frequently Asked Questions
Can I import constants from a file in a parent directory?
Yes, but it is more complex. You may need to modify sys.path using sys.path.append("..") or run your script as a module from the root directory using the -m flag. Generally, it is better to structure your project so that constants are in the same directory or a subdirectory.
Is it better to use a .py file or a .json file for constants?
Use a .py file if your constants are fixed and you want the benefit of IDE autocompletion and type checking. Use a .json or .yaml file if the constants need to be changed by non-programmers or updated without modifying the source code.
Does importing constants slow down my program?
The impact is negligible. Python imports a module only once per session. Subsequent imports of the same module simply reference the already loaded module in sys.modules, so there is no significant performance penalty.
How do I handle constants that change based on the environment (Dev vs Prod)?
The best practice is to use environment variables. You can create a constants.py file that reads from the environment using os.getenv("API_URL", "http://localhost:8000"), providing a default value for development while allowing the production server to override it.
Can I use a class to store constants?
Yes, wrapping constants in a class (e.g., class Config: API_KEY = "...") can help organize them and avoid naming collisions. You can then import the class and access variables via Config.API_KEY.