Layered INI Config With configparser
Layer defaults and environment overrides with configparser read_string calls, keeping configuration precedence explicit and easy to test.
Code
import configparser
defaults = """
[server]
host = 127.0.0.1
port = 8000
debug = false
"""
production = """
[server]
host = 0.0.0.0
port = 8080
"""
config = configparser.ConfigParser()
config.read_string(defaults)
config.read_string(production) # 后读的层覆盖同名的键
section = config['server']
print('host:', section['host'])
print('port:', section.getint('port'))
print('debug:', section.getboolean('debug'))
print('sections:', config.sections())
print('keys:', sorted(section.keys()))How it works
Module-level bindings hold the data — defaults, host, port, debug — with no function scope in between.
What to watch for
- Plan for an install step:
configparseris a real dependency, resolved by the package manager.
Using it
Running the file prints labeled results such as host:, port:, debug: — each operation’s effect is visible in the output.
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Do I need to install anything before running this?
- Yes: `configparser` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.