Logging and configuration boundaries
Make diagnostics useful without leaking secrets or hiding invalid settings.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain logs are an operational interface
- Apply parse settings once and fail clearly
- Reason about redaction is not permission
Logs are an operational interface
A log is a diagnostic event with a severity and selected context. It should explain a safe operational fact without copying private records or secret values.
Understand first
A service needs diagnostics that remain useful when ordinary output is not watched. Logging separates event creation from filtering and destinations. Know strings, finally and object methods first; this fixture uses only a safe synthetic count.
Words you will see
- Severity
- The importance level of an event, such as DEBUG, INFO, WARNING or ERROR.
- Handler
- An object that sends selected log records to a destination.
- Formatter
- The rule used to turn a record into display text.
Follow one event through the route
The standalone Logger has an INFO threshold, so the DEBUG event is ignored. The INFO call stores a message template and count argument. The StreamHandler writes the formatted INFO:processed=2 line into buffer. print displays that actual buffer content.
Using logging.Logger directly here keeps the fixture independent from the root logger and registry configuration. In an application, named loggers from getLogger normally participate in the configured hierarchy. Library code should not replace the application's handlers or force a global basicConfig.
Choose the smallest safe diagnostic
Log a count or documented safe event code instead of a whole request object. Severity should describe operational meaning: INFO for expected events, WARNING for a condition needing attention, ERROR for a failed operation. Severity does not decide which private data is permitted.
finally detaches and closes the handler, then closes the separately owned stream. The handler does not own every object the message refers to, and StreamHandler.close does not generally close a supplied stream. No external logging service, files, tokens or user data are involved.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
logger = logging.Logger('lesson', level=logging.INFO)Create an isolated diagnostic object with an explicit threshold.
logger.addHandler(handler)Route selected records to the owned memory destination.
logger.debug('not selected')Drop a lower-severity record.
logger.info('processed=%s', 2)Emit one safe count using a template and argument.
logger.removeHandler(handler)Detach the destination during cleanup.
Use structured context such as operation, safe identifier and outcome. Distinguish debug detail, normal events, warnings and failures. Avoid printing tokens, passwords, private source or complete personal records into logs.
Conceptual local logging route; not an external log service
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- EventApplication emits an INFO event with safe count 2.
- PolicyAn owned logger filters by severity and formats the message.
- DestinationA StringIO handler receives the event; the root logger is untouched.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Select the debug event too.
Try: Change level=logging.INFO to level=logging.DEBUG.
The buffer now contains DEBUG:not selected followed by the INFO line.
Change formatting, not the event.
Try: Use '%(message)s' as the Formatter template.
The output becomes processed=2 without a severity prefix.
Before you move on
If this logger's threshold becomes WARNING, does the same INFO call reach buffer?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. INFO is below WARNING, so no event line is written. Changing the threshold does not make unsafe message content safe.
Parse settings once and fail clearly
Configuration parsing turns supplied strings into checked application values. A default is a documented value for absence, not permission to hide malformed input.
Understand first
An application needs a numeric limit, but environment-style configuration arrives as text. Parse once at startup and pass the checked integer into later logic. A supplied mapping makes both defaults and invalid values testable without inspecting real machine settings.
Words you will see
- Default
- The chosen value used when an optional setting is absent.
- Validation
- Checking that a value meets the required shape and range.
- Boundary
- The point where external representation becomes an application's trusted value.
Check syntax before numeric range
get returns the supplied LIMIT text or '3' if the key is absent. isascii and isdecimal jointly accept only nonempty ASCII decimal digits here. int then produces an integer, and the inclusive range permits one through nine.
The mapping contains '4', so the first output is integer 4. The empty mapping uses the documented default 3. Reading does not insert LIMIT or rewrite its text. A present empty string fails validation; it is not treated as absence.
Fail deliberately instead of inventing a usable value
A malformed or out-of-range setting raises ValueError with the setting name and rule, not its raw value. A production startup boundary can attach this safe message to an actionable failure. Catching every error and returning 3 would conceal an operator's mistake.
The fixture contract accepts string values; a broader API should check types too. Do not use real os.environ in a browser demonstration or dump it into logs. Defaults for optional limits are different from silently substituting missing security configuration.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
raw = settings.get('LIMIT', '3')Distinguish a missing optional setting from an invalid present one.
value = int(raw)Convert checked digit text to a number.
if not 1 <= value <= 9:Reject values outside the inclusive permitted range.
print(settings)Show that parsing did not change the supplied mapping.
Environment variables are strings. Parse booleans, integers, ranges and required values explicitly at startup; bool('false') is True. Keep defaults limited to documented optional settings, not silent substitutes for missing security configuration.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try the lower boundary.
Try: Set settings = {'LIMIT': '1'}.
The first result is 1 and the mapping remains unchanged.
Try a malformed present value.
Try: Set settings = {'LIMIT': 'four'}.
The run raises ValueError before displaying a successful result.
Before you move on
For {'LIMIT': '0'}, should the default three be returned?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The setting is present but out of range, so ValueError is raised. A default applies only to absence in this contract.
Parse an explicit boolean
A boolean flag needs an explicit text parser. String truthiness says whether text is empty, not whether the text means true or false.
Understand first
A feature flag arriving as 'false' must disable the feature rather than enable it through nonempty-string truthiness. The original parser gives the input a small, stated vocabulary. Understand string methods, set membership and comparisons first.
Words you will see
- Truthiness
- How a value behaves in a boolean test; nonempty strings are truthy.
- Normalisation
- A deliberate conversion to one spelling before checking a value.
- Allowlist
- An explicit set of accepted values, with everything else rejected.
Follow the original normalisation
strip removes surrounding whitespace and lower maps the accepted English spellings to lowercase. ' false ' becomes 'false'; 'TRUE' becomes 'true'. The membership test rejects anything outside those two values before the return expression runs.
value == 'true' returns an actual bool. It is False for the first input and True for the second. The parser does not modify the original string because strings are immutable. It does not accept yes, on, 1 or an empty string.
Keep permissive and strict policies separate
Accepting more spellings can be reasonable, but that is a different contract with more cases to document. Using bool(text) accepts every nonempty spelling, including 'false' and misspellings, so it is not a substitute for this parser.
The example expects a string. A reusable API should reject non-string input deliberately rather than rely on an incidental AttributeError. Invalid text raises instead of silently turning into False, because a typo should not masquerade as an intentional setting.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
value = text.strip().lower()Turn the accepted whitespace/case variants into one spelling.
if value not in {'true', 'false'}:Reject all other text, including an empty string.
return value == 'true'Return an actual boolean from the checked spelling.
print(parse_flag(' false '))Display False despite a nonempty original string.
print(parse_flag('TRUE'))Display True for the uppercase accepted spelling.
Only the documented spellings are accepted; invalid values raise an actionable error instead of becoming truthy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe truthiness separately.
Try: Add print(bool('false')) after the original calls.
The new line is True, showing why explicit parsing is necessary.
Reject an unsupported shorthand.
Try: Change the first argument to '0'.
ValueError stops the run; zero text is not part of this flag vocabulary.
Before you move on
Does the fresh value ' off ' return False in this original parser?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Normalisation makes 'off', which is not allowed, so ValueError is raised. Only true and false spellings are accepted.
Where this idea earns its place
Operational diagnostics should help someone distinguish a bad input, an unavailable dependency and a programming defect without exposing private data. Configuration determines how the application behaves before requests arrive, so parse it once under explicit rules rather than allowing every function to interpret environment strings differently.
Follow the mechanism step by step
Environment variables arrive as strings. Convert each required field using a documented parser, validate its range and reject unknown enum values. Logging separates event creation from handlers and formatting; a library can emit to a named logger without taking over the host application's global handler configuration.
Work through a concrete application
For a service limit, parse an integer, verify it is positive and bound it to a safe maximum. For a flag, accept explicitly named spellings rather than bool(text). Emit a safe startup summary containing enabled capabilities and limit names, not secret values. At request boundaries attach a correlation ID and outcome to diagnostics.
Failure cases and misleading shortcuts
Do not replace a missing signing key with an empty string or a plausible placeholder that lets startup appear successful. Broad object serialization can leak credentials even when a few known field names are redacted. Repeatedly adding handlers during imports can duplicate log output and make the event volume misleading.
Cost, ownership and alternatives
Verbose logging consumes CPU, I/O and retention budget, and expensive formatting can happen even when a message is discarded if built eagerly. Select bounded diagnostic fields and sample carefully without hiding important failures. Retention and access control remain necessary even for supposedly internal logs.
Verify the contract
Test missing, malformed, boundary and conflicting configuration values before serving traffic. Capture logs in tests and assert that relevant context is present while known secrets are absent. Test that importing a library does not unexpectedly configure global logging or start external connections.
Transfer question: What should happen when a required configuration value is invalid?
Fail startup with a safe actionable message identifying the setting and allowed shape, not its secret contents. Silent fallback can produce an application that looks healthy while operating under the wrong security or resource policy.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Parse an explicit boolean
Without copying the worked code, reproduce its observable contract: Only the documented spellings are accepted; invalid values raise an actionable error instead of becoming truthy. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guide: parse a strict boolean flag
Accept only documented text spellings and reject wrong types deliberately.
The contract
- Input may be any object. Non-strings raise TypeError. Strings accept true/false after surrounding whitespace removal and lowercasing.
- Return an actual bool. Empty strings, yes, 0 and arbitrary other text raise ValueError, not a default.
- Do not read host environment values, change input or print/log the raw input.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- true type
r = parse_bool('true') assert type(r) is bool and r is True - false truthiness trap
r = parse_bool('false') assert type(r) is bool and r is False - case whitespace
r = parse_bool(' \tFaLsE\n') assert type(r) is bool and r is False assert parse_bool(' TRUE ') is True - empty rejection
r = parse_bool('true') assert type(r) is bool and r is True for text in ['', ' ']: try: parse_bool(text) except ValueError: pass else: raise AssertionError('Reject empty flag') - unsupported spellings and types
r = parse_bool('false') assert type(r) is bool and r is False for value, error in [('yes', ValueError), ('0', ValueError), ('tru e', ValueError), (0, TypeError), (None, TypeError)]: try: parse_bool(value) except error: pass else: raise AssertionError('Reject unsupported input') - repeat and preservation
text = ' TRUE ' r = parse_bool(text) assert type(r) is bool and r is True assert text == ' TRUE ' and parse_bool(text) is True
Why are TypeError and ValueError separate?
One says the representation is not text; the other says text has an unsupported meaning. Normalisation scans n characters in O(n) work and creates text, not a shared mutable result.
Guide: read an optional bounded limit
Parse a safe numeric setting without changing the supplied mapping.
The contract
- Input is a dict. Absent LIMIT defaults to integer 3. A present value must be a nonempty ASCII digit string representing 1..9.
- Return int, not bool. Present wrong types or malformed/out-of-range text raise ValueError with exactly 'Invalid LIMIT'. Leading zero text such as '04' is allowed.
- Do not mutate the mapping, substitute defaults for invalid present values, read the environment or include raw values in errors.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal integer
r = config_limit({'LIMIT': '4'}) assert type(r) is int and r == 4 - missing default
settings = {} r = config_limit(settings) assert type(r) is int and r == 3 and settings == {} - boundaries and zeros
r = config_limit({'LIMIT': '01'}) assert type(r) is int and r == 1 assert config_limit({'LIMIT': '9'}) == 9 - malformed text
r = config_limit({}) assert type(r) is int and r == 3 for raw in ['', ' ', '-1', '+2', '2.0', '٢']: try: config_limit({'LIMIT': raw}) except ValueError as error: assert str(error) == 'Invalid LIMIT' else: raise AssertionError('Reject malformed present value') - range and type errors
r = config_limit({'LIMIT': '2'}) assert type(r) is int and r == 2 for raw in ['0', '10', 4, None, False]: try: config_limit({'LIMIT': raw}) except ValueError as error: assert str(error) == 'Invalid LIMIT' else: raise AssertionError('Reject invalid type or range') - source preservation
settings = {'LIMIT': '04', 'OTHER': ['fixture']} other = settings['OTHER'] r = config_limit(settings) assert type(r) is int and r == 4 assert settings == {'LIMIT': '04', 'OTHER': ['fixture']} and settings['OTHER'] is other assert config_limit(settings) == 4
What does the default promise exclude?
It excludes malformed present values. Startup should fail with a safe setting-specific error instead of concealing an incorrect configuration. Parsing scans the supplied text and retains no shared mutable result.
Transfer: select a safe diagnostic schema
Change from parsing one setting to publishing a small approved event record.
The contract
- Input is a dict. It must contain operation as one of 'load'/'save' and count as an exact int (not bool) in 0..99; otherwise raise ValueError('Invalid event').
- Return a fresh dict with exactly operation then count, containing those scalar values. Ignore every other field without logging, printing or copying it.
- Do not mutate input or retain a shared result. This narrow schema is not a general sanitizer or permission to log private data.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- approved output
r = safe_event({'operation': 'load', 'count': 2, 'extra': 'fixture-only'}) assert type(r) is dict and list(r.items()) == [('operation', 'load'), ('count', 2)] assert type(r['operation']) is str and type(r['count']) is int - missing fields
r = safe_event({'operation': 'save', 'count': 1}) assert type(r) is dict and r == {'operation': 'save', 'count': 1} for value in [{}, {'operation': 'load'}, {'count': 2}]: try: safe_event(value) except ValueError as error: assert str(error) == 'Invalid event' else: raise AssertionError('Reject missing fields') - range and bool
r = safe_event({'operation': 'load', 'count': 0}) assert type(r) is dict and r['count'] == 0 assert safe_event({'operation': 'save', 'count': 99})['count'] == 99 for count in [-1, 100, True, '2', None]: try: safe_event({'operation': 'load', 'count': count}) except ValueError as error: assert str(error) == 'Invalid event' else: raise AssertionError('Reject count') - operation allowlist
r = safe_event({'operation': 'load', 'count': 1}) assert type(r) is dict and r['operation'] == 'load' for operation in ['LOAD', 'delete', '', None, []]: try: safe_event({'operation': operation, 'count': 1}) except ValueError as error: assert str(error) == 'Invalid event' else: raise AssertionError('Reject operation') - exclude new fields
record = {'operation': 'save', 'count': 3, 'new_field': {'text': 'fixture-only'}} r = safe_event(record) assert type(r) is dict and r == {'operation': 'save', 'count': 3} assert list(r) == ['operation', 'count'] and 'new_field' not in r - fresh result and input ownership
record = {'operation': 'load', 'count': 4, 'extra': []} extra = record['extra'] a = safe_event(record) b = safe_event(record) assert type(a) is dict and type(b) is dict and a == b == {'operation': 'load', 'count': 4} assert a is not b and a is not record a['count'] = 8 assert b['count'] == 4 and record == {'operation': 'load', 'count': 4, 'extra': []} and record['extra'] is extra
Why isn't a denylist equivalent?
A new field would slip through a denylist, while this schema excludes it automatically and validates approved values. Constant schema size bounds selection work; each output is a new dictionary of immutable scalars.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneLogging cost and ownership
Lazy logging formatting delays combining a template and arguments until a record is formatted. Python still evaluates function-call arguments before the logging call can filter them.
Understand first
Diagnostic work should not surprise a hot path. Template arguments avoid eager message interpolation, but they do not postpone arbitrary computations used as arguments. Learn ordinary function-call evaluation before attributing laziness to the whole call.
Words you will see
- Eager evaluation
- Computing an expression before passing its value to a function.
- Deferred formatting
- Combining a message template with values later, when formatting is needed.
- Level guard
- An explicit check that a severity is enabled before doing extra work.
Separate the two costs
compute appends a visible marker and returns 7. Python calls it before logger.debug receives the arguments. The WARNING threshold then rejects DEBUG, but the marker already exists. The %s template delays formatting, not that function call.
isEnabledFor(DEBUG) is False, so the guarded second call never evaluates compute. The buffer remains empty because neither DEBUG event is selected. repr makes that empty string visible as two quotes rather than an unexplained blank output area.
Do not turn logs into application control flow
Use a guard for genuinely costly diagnostic preparation. Do not put required side effects only in a log argument or inside a severity guard; changing logging settings should not change business correctness. Ordinary cheap values can simply be passed as template arguments.
The standalone logger and memory stream avoid global configuration. Cleanup detaches the handler and closes both owned objects. The marker contains no sensitive information, and no timing claim is inferred from this demonstration.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
calls.append('computed')Make evaluation observable without measuring time.
logger.debug('count=%s', compute())Evaluate compute first, then discard the disabled record.
if logger.isEnabledFor(logging.DEBUG):Skip the second computation because DEBUG is disabled.
print(repr(buffer.getvalue()))Show an actually empty local destination.
Use lazy formatting arguments for the logging API rather than eagerly building expensive strings. Configure handlers at the application boundary; libraries should not unexpectedly replace the host application's logging configuration.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Enable debugging.
Try: Change the logger threshold to logging.DEBUG.
Both computations run, calls has two markers, and buffer contains two count=7 lines.
Guard both calls.
Try: Put the first debug call inside its own isEnabledFor(DEBUG) condition.
With the original WARNING threshold, calls becomes [] and buffer stays empty.
Before you move on
If the same code uses logger.debug('x=%s', 2 + 3), is the addition skipped when DEBUG is disabled?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Python evaluates 2 + 3 before calling debug. Only later message formatting is deferred; a level guard is needed to skip expensive argument work.
Redaction is not permission
Selecting safe fields is stronger than copying a record and deleting a few known secret names. An allowlist makes newly added fields excluded by default.
Understand first
A record can grow new fields over time. Removing a few forbidden names leaves new fields exposed; choosing a small safe schema excludes them. This fixture uses no real secrets or personal records, so the lesson does not teach by leaking them.
Words you will see
- Field selection
- Building a new record from explicitly permitted keys.
- Denylist
- A list of known forbidden items, which may miss new ones.
- Shallow copy
- A new outer container that still shares nested objects.
Choose the diagnostic contract before copying
The allowed tuple fixes both field membership and display order. The comprehension copies operation and count if present; extra is never copied. Changing the source count to another integer later does not rewrite the already selected integer binding in safe.
This is not recursive redaction. If an approved value were a mutable nested object, safe would share it unless deliberately copied and checked. A production log boundary should validate approved value types, lengths and content rather than trusting every value under an approved key.
Privacy is more than message shape
A safe field name can still carry private content if callers put it there. Use synthetic or documented non-sensitive identifiers, avoid arbitrary object repr, and define access and retention policies for actual log stores. Redacting text is not permission to record everything else.
For this small in-memory schema, selection visits a fixed number of keys and creates a fresh dictionary. It does not mutate the source or configure any logger. Missing approved keys are skipped intentionally; a required operational field would need a separate validation rule.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
allowed = ('operation', 'count')Define exactly what may cross the boundary.
safe = {key: record[key] for key in allowed if key in record}Build a new outer mapping without extra.
record['count'] = 3Replace a source binding after selection.
print(safe['count'])Print the earlier selected integer 2, not the new source binding.
Redacting a few field names does not make arbitrary objects safe to log. Select allowed diagnostic fields. Keep secret values outside source/config examples, rotate them through the appropriate control plane and define retention for diagnostic records.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe exclusion by default.
Try: Add 'new_field': 'fixture-only' to record.
safe stays limited to operation and count.
Observe a missing optional field.
Try: Remove the count entry from the original record and remove the later assignment/lookup lines.
The selected result contains only operation and extra remains excluded.
Before you move on
If safe includes a list value from record and record's list is appended to, does safe see the append?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. This shallow selection shares nested values. For logging, prefer validated scalar values or deliberately prepare an independent approved representation.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.