Content · Programming · Python

Python Read Configuration Files Without Hardcoding Values

Load program settings from a separate file instead of embedding environment-dependent values. TOML works well for configuration because it supports basic values and sections.

4 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This Python tutorial explains Read Configuration Files Without Hardcoding Values. Follow the example, inspect the output, and practise an input change so you understand the behavior rather than simply copying the syntax.

What This Feature Does


Load program settings from a separate file instead of embedding environment-dependent values.

TOML works well for configuration because it supports basic values and sections. tomllib.load() reads a binary file stream, while tomllib.loads() parses a string. Configuration values must still be validated, and secrets should be handled through secure environment-specific mechanisms.

When to Use It


This technique belongs to persistent data and serialization. It is useful when the input, operation and expected outcome are known. Start with a small controlled example before integrating it into a larger workflow.

Step-by-Step Python Example


Read the code once before running it. Notice which values are inputs, which function or method performs the work, and whether the result is returned or stored by changing an existing object.

from pathlib import Path
from tempfile import TemporaryDirectory
import tomllib

with TemporaryDirectory() as directory_name:
    configuration_path = Path(directory_name) / "settings.toml"
    configuration_path.write_text('[server]\nport = 8080\nmode = "development"\n', encoding="utf-8")
    with configuration_path.open("rb") as configuration_stream:
        settings = tomllib.load(configuration_stream)
    print(settings["server"]["port"])
    print(settings["server"]["mode"])

Understanding the Code


  • First, the imports make pathlib, tempfile, tomllib available. They provide the filesystem, data or standard-library functions used later.
  • Find the call TemporaryDirectory(). Its parameters determine the specific operation demonstrated in the title.
  • Its purpose is to load program settings from a separate file instead of embedding environment-dependent values. Compare this description against the result printed by the program.
  • The sample uses TemporaryDirectory() so any practice files are removed after the context ends; it does not work on your real documents.
  • The print() expressions display a checkable outcome. Print values and exception names are not substitutes for the program result itself.

Expected Output


8080
development

Each printed line corresponds to a separate observation in the program. Use the lines to distinguish returned data, changes to existing objects, and status checks.

Important Details and Edge Cases


Use a predictable configuration lookup path rather than relying on whatever happens to be the current working directory.

Never place passwords or API secrets in configuration files committed to public or shared repositories.

Second Example: A Useful Variation


import tomllib

def read_database_port(configuration_text):
    settings = tomllib.loads(configuration_text)
    port = settings.get('database', {}).get('port', 5432)
    if type(port) is not int or not 1 <= port <= 65535:
        raise ValueError('Invalid database port')
    return port

print(read_database_port('[database]\nport = 5433\n'))

The caller can change the port in configuration instead of modifying program logic, while validation rejects inappropriate values.

Variation Output


5433

Practice: Try It Yourself


Add a feature flag to the TOML file and validate that its value is boolean.

Begin by copying the example into a separate practice file. Change one input at a time, run it again, and describe why the result changed. If the exercise writes or deletes files, keep it inside a temporary test folder.

Official Python Documentation


For the complete reference, see the Python standard library documentation.

Common Beginner Mistakes


  • Hardcoding passwords or API keys in source code or committing them to version control.
  • Assuming that parsed configuration always contains every required section and correct value type.
  • Never place passwords or API secrets in configuration files committed to public or shared repositories.

Key Takeaways


  • Load program settings from a separate file instead of embedding environment-dependent values.
  • TOML works well for configuration because it supports basic values and sections. tomllib.load() reads a binary file stream, while tomllib.loads() parses a string. Configuration values must still be validated, and secrets should be handled through.
  • Avoid this common pitfall: Hardcoding passwords or API keys in source code or committing them to version control.
Share this resourceSend this page to someone who may find it useful.