Back to Explore
GuideVibeFix editorialUpdated Nov 24, 2026

Stop Hard-Coding Python Config: Layer Defaults, Files, and Env Vars

Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.

Real photo: a laptop showing a code editor on a wooden desk, with a pair of glasses beside it

The most common flaw AI-generated code leaves behind is not wrong logic, it is hard-coded config: the port number, how many items to show per page, the debug switch, where the database lives, all written directly in the code. When the project first runs, nothing feels wrong. Then you move it to another machine, hand it to someone else, or deploy it to a server, and all the trouble arrives at once: changing one port means changing code, and changing code means redeploying; a secret slips into the repository along with the code; your own computer and the server end up sharing the same settings, and there is no clean way to separate them. This guide uses a fictional reading-notes app called readlog, and only the Python standard library — os.environ, configparser, and the ideas behind json — to split config into three layers: defaults in the code, a config file the user can edit, and environment variables that override everything. The demo script is demo249_g1.py, run on Python 3.12.3, and the Chinese and English runs share the same logic, so the numbers are identical and each transcript is saved in this directory.

The conclusion first: after all three layers, the effective port is 9090, the page size is 25 items, the debug switch is off, the timeout is 30.0 seconds, the theme is dark, and the database path is ./data/notes.db. How those numbers came about can be said in one sentence: the code defaults say port 8000 and 20 items per page, the config file changes that to port 8080 and 50 items per page, and the environment variables finally change it to port 9090 and 25 items per page. Each layer only changes the keys it cares about, and any key it does not mention keeps the value from the layer below. The debug switch follows the same path: the default is off, the config file turns it on, the environment variable turns it back off, so the final value is off. The theme key was changed to dark by the config file, and since the environment variables never mention it, it stays dark. Remember this order; every detail that follows is an expansion of it.

Why config should be layered

Before layering, ask one question: what actually counts as config? The config chapter of the Twelve-Factor App gives a practical test: config is everything likely to vary between deploys, including database addresses, credentials for external services, and each deploy's own hostname. Code does not vary between deploys, config does, so the two must be strictly separated. The chapter also offers a litmus test: if your codebase were made open source right now, would it leak any credentials? If yes, the config has not been separated from the code yet. That test is a good fit for checking vibe projects: AI-generated code often writes secrets and addresses straight into files, it runs fine, but it fails this question.

The same chapter explains why environment variables are a good place for config: you can change an env var without changing code, and env vars are very unlikely to be accidentally committed to a repo. Config files are already a big improvement over constants hard-coded in the code, but they can still be committed by mistake, and their formats differ from place to place and scatter across the project, which makes them hard to manage in one place. Layering combines the strengths of both sides: the code holds only defaults that everyone can see, so the program runs as soon as you get it; the config file holds the user's own preferences, editable and excludable from version control; the environment variables hold whatever belongs to each deploy, especially secrets and ports that change whenever the deploy changes, affecting only the current run without touching code or files.

The order of the layers matters too: the weakest at the bottom, the strongest at the top. Defaults are weakest, the config file overrides the defaults, and the environment variables override the config file. This order is not arbitrary; it matches how close each layer is to this particular run. The defaults are what the author thought when writing the code, the config file is the user's preference, and the environment variables are the reality of this deploy. The closer to this run, the more it should count. The port number in the demo is the best example: 8000 is the author's default, 8080 is the user's preference, 9090 is what this deploy actually needs, and 9090 is what finally takes effect. Once the layering rule is set, every future config change starts with one question — which layer does this change belong to — and you stop changing the wrong place.

Layer one: defaults in the code

Section 1 of the demo uses only the code defaults, 7 keys: in the app section, port 8000, 20 items per page, debug off, timeout 30.0 seconds, light theme; in the storage section, data directory ./data and database file name notes.db. The defaults are written in one go with configparser.ConfigParser() plus read_dict, written as an ordinary dictionary and read back the same way. Defaults have one hard requirement: they must be the set that lets the program run the moment you get it, with no missing key and no file the user has to create first. The demo defaults satisfy this: port, page size, debug, timeout, theme, data directory, and database file name are all present, no file is read, no environment variable is read, and the program can still start.

Defaults have another requirement that is easy to overlook: they must be safe. Port 8000 is a local port, debug is off by default, the data directory is a relative path inside the project, and there is no secret anywhere. The Twelve-Factor litmus test applies here as well: defaults travel with the code into the repository, so they must never contain a real secret, a real password, or a real token. The demo deliberately leaves a key called api_key out of the defaults and out of the config file, and Section 5 explains how it should be handled. When writing defaults, ask one more question — is it a problem if this value goes into the repository — and you avoid a lot of cleanup later.

One more thing to note: the numbers and switches in the defaults are all strings as far as configparser is concerned. The 8000 is stored as the string "8000", 30.0 as the string "30.0", and the debug "no" as a string too. The official docs state this plainly: the parser does not guess datatypes, all values are stored internally as strings, and you convert them yourself when you need another type. Section 4 explains how to convert; for now, remember this premise, because many of the traps later come from it.

Layer two: a config file the user can edit

Section 2 of the demo adds the config file, and 4 of the 7 keys change: the port goes from 8000 to 8080, the page size from 20 to 50, debug from off to on, and the theme from light to dark; the timeout, data directory, and database file name are not mentioned, so they keep their defaults. The config file is in INI format, easy to recognize: square brackets mark a section, like [app] and [storage], and under each section there is one key-value pair per line, separated by an equals sign or a colon, with lines starting with # or ; as comments. The demo file is a string written inside the script and read with read_string; in a real project it would be a readlog.ini file read with config.read, written the same way.

The official docs note several details about the INI format that you will run into sooner or later, and knowing them early saves trouble. First, section names are case sensitive but keys are not, and keys are stored internally in lowercase, so Port and port are the same key; Section 6 verifies that config['app']['PORT'] reads back 9090, exactly the same as lowercase port. Second, values can span multiple lines as long as the continuation lines are indented deeper than the first line, comments belong on their own lines, and inline comments are not recognized by default — do not add a comment after a value, it becomes part of the value. Third, when several config files are read, the later one overrides the earlier one: conflicting keys take the later value, non-conflicting keys are kept. That is the same behavior as the three-layer stacking in the demo, just between config files.

There is one more practical property of this layer: a missing file is not an error. Calling config.read with a filename that does not exist returns an empty list, and the program keeps running on its defaults; Section 6 verifies that reading no-such-file-249.ini returns []. That behavior fits an optional config file: if the user has one, use it, and if not, use the defaults, and the program runs in both cases. But it also means a typo in the filename or a file in the wrong path will not tell you anything — the program will silently run on defaults while you believe your config took effect. So the first time a new project runs, print the effective config once, listing all 7 keys the way the demo does, and see it with your own eyes.

Layer three: environment variables have the last word

Section 3 of the demo adds the environment variables, and 3 of the 7 keys change again: the port goes from 8080 to 9090, the page size from 50 to 25, and debug from on back to off; the theme stays dark, because the environment variables never mention it. Environment variables are key-value pairs at the operating system level; in Python you read them with os.environ, which is a dictionary, and os.environ["READLOG_PORT"] returns the string "9090". To keep the demo repeatable, the script sets these three variables itself; in a real project they come from the launch command or the deploy platform, for example READLOG_PORT=9090 python app.py, and the program reads the same values.

Environment variable names should share one prefix; the demo uses READLOG_, with three variables, READLOG_PORT, READLOG_PAGE_SIZE, and READLOG_DEBUG. A prefix has two benefits: it will not collide with other variables in the system, and you can tell at a glance which variables belong to this app, so searching for the prefix is enough when something goes wrong. The Twelve-Factor chapter also stresses that env vars are managed as granular, independent controls, each one on its own, not grouped into named environments like development or production; the demo's three variables are three independent switches, changing the port does not touch the page size, and changing debug does not touch the port.

What belongs in this layer? Two kinds of things: values that differ from deploy to deploy, like ports and hostnames, and things that must never enter the repository, like secrets and tokens. The deliberately missing api_key in the demo belongs to the second kind; its proper home is an environment variable, not the defaults and not the config file. The other way around, one kind of thing does not belong in environment variables: internal settings that do not vary between deploys, such as how routes are written or how code modules are connected. Those stay in the code; the Twelve-Factor chapter says explicitly that they are not config and do not need to go into env vars.

Grouped bar chart: measured in the demo, port across the three layers is 8000, 8080, 9090, and page size is 20, 50, 25 items

The chart above shows the three layers stacked, and the numbers match the demo transcript exactly. On the left is the port: the default 8000, the config file changes it to 8080, and the environment variable finally changes it to 9090, each layer higher than the last, and the highest one is what takes effect. On the right is the page size: the default 20, the config file changes it to 50, and the environment variable finally changes it to 25. Here the environment variable makes the number smaller, a reminder that having the last word does not mean the number keeps growing — each layer is an independent decision. Together the two charts are the core conclusion of this guide: layer your config, let each layer change only the keys it should change, and the effective value is always the result of all three layers stacked, never one layer alone.

Type conversion: everything in the file is a string

Section 4 of the demo covers the easiest trap to fall into: everything in the config file is a string, and you must convert it to the type you need before using it. In the demo's final config, port 9090 is an integer, timeout 30.0 is a float, and debug False is a boolean, converted with getint, getfloat, and getboolean respectively. The official docs are clear on this: the parser does not guess types, but it provides these three conversion methods, so you do not have to write int(...) yourself or handle conversion failures by hand. For other types, such as a list, convert first and then process it yourself, for example by splitting on commas, and do that step where the config is loaded, not scattered through the business code.

Booleans deserve their own paragraph, because they hide a classic trap: converting a string with plain bool() is always wrong. The demo verifies that bool("False") returns True, because in Python any non-empty string is truthy, even when its content is the word False. The correct tool is getboolean, which only accepts yes, no, on, off, true, false, 1, and 0, case-insensitively; in the demo the config file's debug = yes converts to True, and the env var's no converts to False, both correct. AI-generated code often contains debug = bool(os.environ.get("DEBUG")), and once the environment variable holds the word False, debug can never be turned off. If you see that pattern, fix it on the spot.

Type conversion has a companion rule: the converted type must match where it is used. The port is an integer, and it cannot be a string when handed to a networking library; the timeout is a float, and it cannot be a string when passed to time.sleep or a request library; the page size is an integer, and it certainly cannot be a string when used for pagination math. The demo prints all three converted results, port 9090 as an integer, timeout 30.0 as a float, debug False as a boolean, each labeled with its type so you can see at a glance that the conversion happened. In a real project, the config-loading function should convert every value at startup, so the rest of the code only ever uses converted values, instead of converting on the spot each time, or converting in some places and not others.

Missing keys: fail early, fail clearly

Section 5 of the demo is about missing keys, and the core idea is one sentence: when a required key is missing, fail at startup, not halfway through a run. In the demo, reading the missing key api_key with config["app"]["api_key"] raises KeyError: 'api_key' right away. The error is simple, but it happens early and its location is clear, so you find it when the program starts, not in the middle of a run while a user is waiting. The docs also offer a gentler option: the get method accepts a fallback, which is returned when the key is missing; the demo verifies that get('api_key', fallback='(not set)') returns (not set) and the program keeps going.

One detail here is easy to get wrong: default values take precedence over fallbacks. The docs state plainly that if a key appears only in the DEFAULT section, reading it always returns that default, no matter what fallback you pass. The demo does not use a DEFAULT section, writing its defaults as ordinary sections instead, so this does not come up in the demo, but in a real project that uses DEFAULT, remember this order. The more general rule is to separate two kinds of keys: required keys get no fallback, and when one is missing, let it fail with a message that says which key is missing and where to set it; optional keys get a fallback, and the fallback value should sit in the most visible place in the code, not hidden in some corner.

There is a companion practice worth adding in a real project: validate all required keys once at startup, report every missing one at once, instead of failing on one, fixing it, and failing on the next. The demo is small, with only one missing key, api_key, but a real project can have a dozen required keys, and fixing them one at a time is miserable. While validating, check the types too: the port must be an integer between 1 and 65535, the page size a positive integer, the timeout a positive number. Put those checks and the missing-key checks in the same place, pass the config gate before the program starts, and the rest of the run is much calmer.

Interpolation and case: two easy traps

Section 6 of the demo covers two small features that are both of the kind you trip over until you know them, and then they feel natural. The first is interpolation: a value in the config file can refer to another key in the same section, written as %(key)s; the demo builds the database path this way, db_path = %(data_dir)s/%(db_name)s, which reads back as ./data/notes.db, the data directory plus the database file name. The benefit is that when the data directory changes, every path built from it changes along with it, instead of each one being edited separately. The docs also say interpolation is computed when the value is read, not when the file is written, so the order of keys in the file does not matter; and if a value genuinely needs a percent sign, write two of them, %%, to escape it.

The second is case: section names are case sensitive, key names are not. The demo verifies that config['app']['PORT'] reads back 9090, the same key as lowercase port. That means Port, PORT, and port in the config file all read as the same value, and a case mismatch will not make a key unreadable. Sections are different: [App] and [app] are two different sections, and a typo there will make the read fail. The safest convention in a real project is to write all section and key names in lowercase with underscores, agree on it once, and follow it everywhere, so case never becomes a debugging clue.

One more result verified in this section: reading a missing config file returns an empty list, [], with no error. It was mentioned before, and it belongs here as a reminder that interpolation and case only matter when the config file was actually read. If the file was never read, the program runs on defaults, and no amount of interpolation written in the file will take effect. So when debugging a config problem, the first step is always to confirm whether the file was read at all, and the way to do that is to print the effective config, listing all 7 keys the way the demo does, and compare it against the file you wrote — one look tells you which layer did not take effect.

Closing checklist and boundaries

Here is everything above as a checklist: write the defaults in the code, so the program runs the moment you get it, and keep secrets out of them; use an INI config file the user can edit and leave out of version control, accept that a missing file is not an error, but print the effective config to confirm; use environment variables with a shared prefix for values that differ per deploy and for secrets, letting them override everything; convert types with getint, getfloat, and getboolean, and never convert a string with bool(); fail at startup when a required key is missing, and use a fallback only for optional keys; build derived values like paths with interpolation, and keep section and key names lowercase. The demo's final config has 8 keys in total, 5 in the app section and 3 in storage, the extra one being the database path built by interpolation, and that number matches the transcript.

Finally, what this guide does not cover, so you do not take these three layers into fights they are not meant for: it does not cover third-party config libraries. The demo uses only the standard library; tools like dotenv are a different approach, and once you understand the three standard-library layers, you will know exactly what they save you. It does not cover encrypting secrets; environment variables keep secrets out of the repository, they do not encrypt them, and real secret management is a separate topic. It does not go deep into TOML; the official docs themselves mention tomllib as an improved version of INI, a good switch when the config gets complex, but get the layering right before switching formats. And it does not cover server-side config centers; for a solo project, three layers are enough. One last boundary note: this guide continues the site's Python basics series. The file I/O guide covered reading and writing JSON, the logging guide covered recording events, the testing guide covered writing assertions; this one covers where a program's settings should live and in what order they take effect before the program runs, and together they make a vibe project go from something that runs to something you can hand to someone else.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles