
Configure with Environment Variables
The same code often runs in different places: your laptop, a test server, production. Settings that change between them (ports, debug mode, API keys) belong in environment variables, not in the code.
import os
port = int(os.environ.get("LANTERN_PORT", "8000"))
os.environ works like a dict of strings. Always:
- Give a sensible default with
.get(key, default). - Convert the type yourself, because everything arrives as text.
- Fail with a clear message when a value is wrong.
Watch out: bool("false") is True, because any non-empty string is
truthy! Compare against a set of accepted words instead.
Keep secrets (passwords, tokens) out of your code and out of git. Read them from the environment, which is exactly what this pattern does.
Taking env as a parameter (defaulting to os.environ) makes the
function easy to test with a plain dict.
Assignment
Write load_config(env=None). Use os.environ when env is None.
Return a dict with:
"name":LANTERN_NAME, default"lantern-network""port":LANTERN_PORTas an int, default8000. If it isn't a number, raiseValueErrorwith a message that mentionsLANTERN_PORT."debug":Trueonly ifLANTERN_DEBUG(any case, ignoring spaces) is one of1,true,yes,on. DefaultFalse.
Write load_config(env=None). Use os.environ when env is None.
Return a dict with:
"name":LANTERN_NAME, default"lantern-network""port":LANTERN_PORTas an int, default8000. If it isn't a number, raiseValueErrorwith a message that mentionsLANTERN_PORT."debug":Trueonly ifLANTERN_DEBUG(any case, ignoring spaces) is one of1,true,yes,on. DefaultFalse.
Press Run to try your code, then Check to test it.