Posts

Showing posts from September, 2026

Reload a fixture module after changing it

importlib.reload() re-executes a module that was imported successfully, using its original loader. This example creates a temporary directory containing fixture_reload.py , adds that directory to sys.path , and imports the fixture. Its first concrete value is "one" . The source is then replaced with a longer assignment whose value is "two changed" ; invalidate_caches() asks import finders to discard relevant discovery caches before reload() is called. Assertions check the first value, that reload returned the same module object in this case, and the newly defined value. The output contains only the final value, so it does not depend on the temporary directory name. The finally block removes this fixture's path entry and module-cache entry even if an assertion fails. Changing the file length also makes this small fixture less dependent on a filesystem timestamp with coarse resolution. Reloading is not a general reset mechanism. Python retains the module dic...

Preserve key case in a ConfigParser

By default, ConfigParser converts option names to lowercase. That is convenient for case-insensitive configuration, but it changes spelling such as APIKey when a parser reads and later writes an INI document. To preserve option-name case, set optionxform to str before reading or setting options. str returns each incoming option name unchanged, which is the idempotent canonicalization behavior the parser expects. This example parses a [headers] section containing APIKey . The key list remains APIKey , retrieval using that exact spelling returns demo-token , and retrieval with lowercase apikey fails. The caught NoOptionError confirms the direct consequence of choosing case preservation: option lookup becomes case-sensitive. Section names have separate behavior and are case-sensitive by default regardless of this setting. Configure optionxform before ingesting configuration, because names already read with the default transformer have already been lowercased. Case preservation ...

List package resource names without assuming filesystem paths

importlib.resources.files() returns a Traversable resource container, not a promise that a package is installed as an ordinary directory. That distinction matters because packages can be imported from mechanisms such as zip files. To list resource names, call files(package).iterdir() and work with each returned object's resource-oriented methods, including name and is_file() . This example creates a temporary package containing alpha.txt and beta.txt , imports it, and asks its resource container for direct children. The comprehension selects only text-file resources and sorts their names, so its output is deterministic: alpha.txt, beta.txt . The assertion checks the expected names for this controlled fixture. The code deliberately does not convert a resource to pathlib.Path , call __file__ , or construct a path relative to an installed package. Those approaches can couple an application to one installation layout. iterdir() is non-recursive, so nested resources require expl...

Use a subcommand to select a dry-run action

argparse subcommands make the selected operation visible in the command shape, instead of making a dry-run behavior depend only on a boolean flag. This example creates a dry-run subparser with one positional target . Its set_defaults() call stores a callable as action , so parsing the synthetic arguments dry-run cache produces a namespace containing the subcommand name, target, and selected action. The action returns a preview string; it does not delete a cache or access the filesystem. The assertions verify that parsing selected dry-run , that the callable produced the expected preview, and that the output is exactly would-delete cache . This keeps parsing and dispatch close together while making the dry-run path explicitly testable. add_subparsers() creates the command group. Passing required=True means parsing without a subcommand is an error; that option requires Python 3.7 or later. set_defaults() can attach arbitrary values to the parsed namespace, but it does not ensure...

Extract numbered issue references without matching prefixes

Issue text can contain a useful reference such as #12 alongside strings where a number sign is part of a larger token. The pattern (?<![A-Za-z0-9_])#(\d+) uses a one-character negative lookbehind before # . It therefore extracts 12 and 7 , but rejects pre#34 and ABC_#56 : in each rejected case, the number sign has an ASCII letter or underscore immediately before it. The capturing group contains only the digits, which is why findall() returns digit strings rather than complete #12 text. The assertion fixes the intended behavior for this input, and the list printout has stable ordering because findall() reports non-overlapping matches from left to right. Python's standard re module supports fixed-width negative lookbehinds; this one is exactly one character wide. Read the official re.Pattern.findall() documentation , the description of negative lookbehind , and the special sequence reference . These APIs are available in current supported Python 3 versions. “Prefix” is ...

Use INI interpolation for a derived local path

INI interpolation can express a derived local path without repeating its base component. ConfigParser uses basic interpolation by default, so %(root)s/cache refers to the root option in the same section. The example reads a paths section where root is the relative local directory local-data ; retrieving cache expands the reference to local-data/cache . The assertions deliberately inspect both forms. get(..., raw=True) returns the stored template, while an ordinary get() returns the interpolated value. This distinction matters for diagnostics and for tools that need to preserve a template rather than consume its resolved setting. Interpolation is resolved when the value is retrieved, so referenced options do not need to appear earlier in the INI text. A derived string is not automatically a usable filesystem location. This example does not create a directory, normalize separators, reject traversal components, or confirm that the path exists. It only demonstrates configuration ...

Inspect a module origin using find_spec

importlib.util.find_spec() can expose a module's ModuleSpec without binding that module name in the current namespace. A spec includes an origin field: for source modules it is commonly a filename, while loaders without a file location can use another meaningful marker. This example looks up the standard-library sys module. In CPython, its expected origin is the exact string "built-in" , so the code asserts that marker and prints the fully qualified spec name plus a deterministic Boolean result. The concrete input is therefore "sys" , not a pathname. The output does not disclose an installation directory and avoids treating origin as a universally usable filesystem path. That distinction matters: a module spec's origin describes the loader's loading location, and namespace packages may have None instead. Furthermore, module.__file__ and module.__spec__.origin are not kept synchronized if either changes at runtime. Inspect a returned spec for d...

Distinguish missing XML text from an empty string

Distinguish missing XML text from an empty string Element.text can be None , an empty string, or a non-empty string in an ElementTree object. Do not write if not element.text when the distinction matters: that condition groups None and "" together. First check whether find() returned an element, then compare its text value explicitly. The example builds three child elements in memory. missing-text has the default None text, empty-text is explicitly assigned "" , and message contains "enabled" ; asking for an absent child forms a fourth case. text_state() returns a separate label for each state, and assertions establish the intended classification before it is printed. There is an important parsing limitation. XML source such as <note></note> and <note/> contains no character data, and ElementTree normally represents both parsed elements with text is None . Consequently, ElementTree cannot recover an author’s lexical choice...

Require an INI section before reading settings

A configuration reader can make its required structure explicit before it asks for individual options. Here, read_service_mode() calls has_section("service") immediately after parsing. If the section is absent, it raises a clear ValueError ; otherwise it reads mode . The example exercises both paths: a valid document produces quiet , and a document containing only [logging] produces the predictable missing-section message. This check is useful when a section represents a required component rather than an optional collection of settings. It distinguishes a missing section from a missing option, so an application can present a focused diagnostic or choose its own fallback behavior. The subsequent get() can still fail if mode itself is absent, and this helper intentionally does not validate whether the returned mode is one of an application's allowed values. Add that validation separately when the setting controls program behavior. The parser's special DEFAULT v...

Write an INI configuration to StringIO

io.StringIO is a text stream kept in memory, which makes it useful when code needs an INI representation without opening a file. In this example, a ConfigParser receives a service section and two string options. Calling write() serializes the configuration into the StringIO destination, and getvalue() returns the complete generated text for comparison and output. The assertion includes every newline, including the blank line that ConfigParser.write() places after the section. That makes the output contract explicit: the printed text is exactly [service] , followed by the two options and a final blank line. The example also shows that values supplied through the mapping interface are strings, matching the INI parser's storage model. write() formats a configuration representation; it does not preserve arbitrary input formatting, comments, or every dialect-specific feature of an original file. It also does not validate that localhost and 8080 identify a running service. A ...

Replace only standalone TODO markers

Replacing every occurrence of TODO can alter text that merely contains those four letters. This example compiles r"\bTODO\b" , then replaces only matches bounded by the regular-expression engine’s word-boundary rule. It changes the leading TODO and the parenthesized TODO to DONE . It leaves preTODOpost unchanged because letters on both sides make the embedded text part of one word. It also leaves TODO_1 unchanged because underscore and digits are word characters. Pattern.subn() returns a pair containing the changed string and the number of replacements. The assertion checks both the complete output and the count of two before printing. That makes the sample’s intended matching behavior explicit, rather than deriving a count from displayed text. Python documents re.Pattern.subn() and \b word boundaries . These are established re APIs; the example requires Python 3 but no newer Python-version feature. A word boundary follows the regex engine’s definition of word char...

Report an invalid repeated separator with finditer

Delimited text can contain an accidental doubled separator even when the surrounding fields look plausible. This example treats adjacent identical colons or semicolons as invalid. The pattern captures one separator in the named separator group and then uses \1+ to require one or more immediate repetitions of that same character. Therefore :: and ;; are reported, while a single ; is not. Pattern.finditer yields match objects rather than only matched strings. Each object supplies the source text through group() and zero-based, end-exclusive offsets through start() and end() . The assertions establish the expected runs and offsets for this concrete input before the reporting loop formats each issue. End-exclusive offsets are convenient for slicing: text[start:end] retrieves the reported run exactly. This is a narrow validator, not a complete parser for a delimiter-based format. It deliberately does not reject mixed adjacent separators such as :; , separators inside quoted field...

Select XML children with a namespace map

XML namespace prefixes in a document are not the names that ElementTree stores internally. It expands namespaced tags to URI-qualified names. A namespace map lets a query use readable local prefixes while supplying the full namespace URI separately. This example parses a short catalog with one default namespace and one meta namespace, then calls findall() with paths that use the map. The map names are chosen by the program; they do not need to match the prefixes used in the XML source. root.findall('book:item', ns) selects the two default-namespace items. On each item, item.find('meta:code', ns) selects its namespaced child. The assertions confirm the two titles and codes, while the output pairs each title with its corresponding code in document order. This approach uses ElementTree’s supported XPath subset, not a complete XPath engine. A query must include the namespace map for each namespaced path, and an unqualified findall('item') would not sele...

Parse --verbose occurrences into a logging level

Repeated verbosity flags are a compact command-line convention, but counting them is separate from choosing logging behavior. argparse supplies action="count" to count occurrences of an option. This article maps that integer with a small, explicit policy: no flags means WARNING , one means INFO , and two or more mean DEBUG . The parser accepts both -v and --verbose . Its default=0 is important: without it, an omitted count option has the default value None . The example parses three synthetic argument lists: [] , [-v] , and [-vv] . argparse recognizes the grouped short form as two occurrences, then logging_level() converts the counts to standard logging constants. logging.getLevelName() makes the deterministic output readable: WARNING INFO DEBUG . The assertion verifies those three cases and the selected policy for them. This is not a universal verbosity scale. In particular, the function intentionally treats three or more occurrences the same as two; a program wanti...

Read a fallback value from DEFAULT in ConfigParser

ConfigParser has two similarly named mechanisms that behave differently. The special [DEFAULT] section supplies inherited option values to ordinary sections. The fallback= keyword of ConfigParser.get() is used only when the requested option is unavailable after normal lookup. A value in [DEFAULT] therefore takes precedence over a fallback= value. This example reads an INI string with color = teal in [DEFAULT] and a separate [ui] section. parser.get("ui", "color", fallback="gray") returns teal : the section does not define color , so lookup inherits it from DEFAULT . The missing font option is absent from both places, so parser.get("ui", "font", fallback="sans") returns sans . The tuple assertion checks both concrete results, and the two printed lines make that precedence visible. This inheritance can make configuration concise, but it also means a section may appear to contain an option that was not written under...

Stream XML records with iterparse

Stream XML records with iterparse ElementTree.iterparse() reports parsing events while it incrementally builds an XML tree. For record-oriented input, handle an "end" event for each completed record: at that point its children and text are available. This example uses an in-memory StringIO fixture containing three <record> elements, collects their identifiers and values, and calls clear() after each record has been read. The assertions demonstrate that each record produced the expected pair and that the numeric total is 23. element.clear() removes the processed element’s attributes, text, tail, and children, so it can reduce retained detail during this style of processing. It must occur only after extracting what the program needs; clearing earlier would make the child lookup fail. The printed output reports the three records and their aggregate. iterparse() performs blocking reads from its source. It is therefore not a non-blocking streaming interface, and it...

Reject a missing module spec before import

A module spec describes how the import system could load a module. importlib.util.find_spec() lets code ask for that description before deciding whether to import. Here, the concrete input is the intentionally nonexistent top-level name "article_fixture_missing_module_8f2c" . The expected result is None , so the program asserts that result, confirms the name is absent from sys.modules , and prints that importing was skipped. This is a useful branch for an optional, controlled dependency: call import_module() only when a spec was found. It is not a security boundary. Finders participate in discovery, and a spec's presence does not make a module trustworthy; importing a discovered module can still execute its top-level code. The test name is selected to avoid colliding with a normal standard-library module, but an environment with a custom importer could deliberately provide it. This check is also not atomic: the import environment can change between discovery and a late...

Use argparse BooleanOptionalAction for a local switch

A local on/off setting is often clearer when users can state either choice directly. argparse.BooleanOptionalAction creates the positive and negative long options from one declaration. Adding --cache with this action also accepts --no-cache ; the first stores True and the second stores False . The example sets default=True , which represents the application's chosen behavior when neither option appears. It then parses three fixed argument lists. An empty list keeps the default, --no-cache disables caching, and --cache explicitly enables it. The assertion checks that the resulting values are [True, False, True] , and print(*values) produces the exact output True False True . Passing lists directly to parse_args() keeps the sample independent of the program that launches it. This action is appropriate for a boolean setting, not a value-taking option. Avoid type=bool for text such as --cache False : Python considers non-empty strings truthy, so that spelling does not express...

Read HTML attributes without regex matching

HTML attributes have quoting, entity-reference, and case-normalization details that are easy to mishandle with a pattern aimed at raw source text. HTMLParser.handle_starttag() supplies a parsed list of (name, value) pairs, so this example reads an image element’s attributes directly instead of applying regular expressions. Converting those pairs to a dictionary makes named lookup clear for this controlled fixture. The input uses uppercase IMG and ALT , single quotes around src , and an entity in alt . The parser normalizes names to lowercase, removes quotation marks from values, and converts the &amp; reference. The assertions make each expected normalized result explicit, and the output is a stable joined summary: logo.svg | Blue & white . There are limits to the convenient dictionary step. HTML allows duplicate attribute names in source, but dict(attrs) keeps only the final value; use the original list if duplicate handling matters. An empty attribute is represented as...

Use re.escape for a literal search token

A search token is not automatically a literal regular expression. In this example, + and ? in a+b? have regex meanings, so compiling the token directly would describe a pattern instead of the four visible characters. re.escape(token) returns a pattern fragment in which characters with regex significance are escaped. The compiled expression then finds the two literal occurrences in the input and ignores the unrelated aab text. The assertions check both the matched strings and their zero-based spans. Spans are useful in diagnostics because they identify the precise part of the original string without modifying it. The printed count and first position make the result deterministic and easy to inspect. Use re.escape for data that must become a literal portion of a regex pattern, including a token inserted into a larger pattern. It does not validate the surrounding pattern or provide a replacement string for re.sub ; Python’s documentation specifically notes that replacement handlin...

Collect text from selected HTML tags with HTMLParser

HTMLParser is useful when a small task needs parser callbacks rather than a CSS-selector engine. This example selects only h2 and p elements from a fixed HTML fragment. handle_starttag() records a new text buffer for a selected tag, handle_data() appends text while that buffer is active, and handle_endtag() finalizes the collected value. The assertions check both selection and encounter order: the aside text must not appear, while the nested em text remains part of its surrounding paragraph. The printed list is therefore ['Setup', 'Use a parser.'] . HTMLParser lowercases tag names before delivering them to handle_starttag() , so the selected tag set is written in lowercase. With its default convert_charrefs=True , ordinary character references are converted before data is delivered; this example does not rely on that behavior. This is deliberately a small callback-based collector, not a complete document model. HTMLParser accepts malformed HTML, but it do...

Validate a whole local identifier with fullmatch

A local identifier rule is often clearer when the pattern describes one identifier and fullmatch() supplies the whole-string requirement. This example accepts an ASCII letter or underscore first, followed by ASCII letters, digits, or underscores. From five candidate values, only local_name and x2 are retained. 2fast fails because its first character is a digit; name-with-dash fails because a hyphen is not included; and name\n fails because the newline is extra input. Pattern.fullmatch() returns a match only when the pattern covers the entire supplied string, so this avoids relying on ^ and $ anchors whose newline behavior can be surprising. The meaningful assertion checks the selected values, while the printed list makes the outcome deterministic. re and Pattern.fullmatch() are standard-library APIs; fullmatch() was added in Python 3.4. The raw string keeps the regular-expression backslashes literal in Python source. See the official re documentation and its character-cl...

Read a package text resource with files

importlib.resources.files() returns a traversable view of resources associated with a package or module. This example builds a temporary package named fixture_resources with an empty __init__.py and one UTF-8 resource, message.txt . After importing the package from the temporary directory, files(fixture_resources).joinpath("message.txt") selects that resource. read_text(encoding="utf-8") produces the exact string "hello resource\n" ; the assertion includes the newline, and repr() makes it visible in deterministic output. The fixture is isolated: it uses TemporaryDirectory , then removes both its temporary sys.path entry and package cache entry in finally . No real user path is printed or required. Passing the imported package object is explicit, so the resource anchor is clear. A traversable resource is not necessarily an ordinary filesystem Path . Packages and resources may be loaded from a zip file, so code that merely needs text should prefer r...

Name groups in a build-label regular expression

A build label is easier to consume when the regular expression names its semantic parts. Here, project , major , minor , and channel are named groups in the label orbit-2.14-rc . After fullmatch() verifies the complete label shape, groupdict() produces a dictionary keyed by those group names. The assertion checks every extracted string, including 14 for the minor version and rc for the channel. Printing the dictionary gives exact, predictable output for this literal insertion order. Python uses the syntax (?P<name>...) for a named capturing group. A named group also has a numeric group number, but using names makes later code less fragile when parentheses are rearranged. Pattern.fullmatch() is used so that a valid-looking substring cannot make a longer malformed label acceptable. The official re syntax documentation describes named groups, and Match.groupdict() documents the mapping returned from a match. Named groups and groupdict() are long-standing standard-library...

Serialize XML with stable attribute insertion order

Serialize XML with stable attribute insertion order When a consumer compares ordinary XML text, attribute order can matter to that consumer even though XML attribute order has no semantic meaning. In Python 3.8 and later, xml.etree.ElementTree.tostring() preserves the attribute order specified by the user. Build or set attributes in the desired order instead of sorting them accidentally through an unrelated transformation. The example creates a <task> element, then calls set() for id , state , and priority in that sequence. tostring(..., encoding="unicode") returns text rather than bytes. The exact-string assertion makes the intended serializer result visible, and the printed line is deterministic for Python 3.8+. This is a serialization convention, not XML canonicalization. It does not mean another XML producer will use the same order, nor does it make two semantically equivalent documents byte-identical when whitespace, namespace declarations, escaping, or oth...

Load a named standard-library module with importlib

importlib.import_module() imports a module from a string name and returns that requested module. This is useful when a program selects from a controlled dispatch table or configuration value. Here, the concrete input is the string "statistics" . The returned module provides mean() , which receives [2, 4, 6] ; the assertion verifies that this calculation produces 4 before the program prints two stable lines. The example intentionally names a standard-library module, so it needs no local fixture or network access. import_module() accepts absolute names and can resolve relative names when a package anchor is supplied. It is a programmatic-import interface, not a validator for arbitrary plugin names: importing executes module-level code. An application should restrict or validate names obtained from untrusted input before importing them. The assertion establishes this one calculation in the running interpreter; it does not establish that every attribute of the imported module...

Use ElementTree.findall for direct child records

Use ElementTree.findall for direct child records Use root.findall("record") when the records you want are immediate children of the current element. It does not recursively descend into nested containers. That makes the selection match a document structure where the root catalogue owns top-level records and a section may contain records with a different role. The synthetic input contains two direct <record> children of <catalog> and one nested <record> inside <section> . The first findall() call returns only identifiers A and B . For contrast, .findall(".//record") uses the supported // XPath form to select records at every depth, producing A , nested , and B . The assertions prove the difference for this particular tree, while the exact output makes the choice visible. This is ElementTree’s limited XPath support rather than a full XPath engine. Namespaced XML needs qualified names or a namespace mapping; a bare "record" ...

Return a controlled parser error for an invalid mode

A command-line parser normally writes an error and exits when it rejects input. For a program that needs to decide its own response, create ArgumentParser with exit_on_error=False . In this example, the positional mode accepts only fast or safe . Parsing the synthetic input turbo raises argparse.ArgumentError , which the program converts into the stable message invalid mode: turbo . The assertion deliberately checks that the parser reported an invalid choice, while the printed result comes from application code rather than from argparse 's formatted diagnostic. That distinction keeps stdout deterministic and avoids coupling a user-facing protocol to parser wording, usage formatting, or future documentation changes. The else branch ensures the example fails if the invalid input is accidentally accepted. This approach handles parser errors that are raised as ArgumentError ; it is not a universal replacement for validating every command-line failure. For example, application-sp...

Read an integer option from an INI string

ConfigParser stores INI values as strings, even when a value looks numeric. Use getint() when the configuration option is specifically an integer: it retrieves the option and applies integer conversion in one call. This example parses a small INI document held entirely in memory, reads retries = 3 from the worker section, and asserts both the numeric value and its Python type before printing retries=3 . The input must name an existing section and option. A missing section raises a configuration-parser lookup error. An option missing from both the named section and its DEFAULT values also raises a lookup error; ConfigParser can inherit values from DEFAULT , so absence from worker alone does not necessarily fail. A present but non-integer value makes getint() raise ValueError . Those outcomes are useful signals when a setting is required; they are not silently converted to a default by this code. If an application accepts an optional setting, it can use the parser-level fallback...

Keep library logging quiet with a NullHandler

A reusable library can describe events through logging without configuring the application's logging system. logging.NullHandler supports that boundary: it accepts log records and performs no output. This standalone example obtains a named library logger, disables propagation for this isolated demonstration, and attaches one NullHandler with the documented addHandler() method. The warning uses a fixed message. The assertions confirm that the handler attached by the example is a NullHandler and that its level permits the warning record. The only stdout text comes from print ; the warning itself produces no handler output. This demonstrates the handler's no-operation behavior without depending on whether a host application's root logger already has handlers. A library normally creates its top-level logger at module scope and attaches a null handler there. It should not call basicConfig() merely to suppress output, because that configures application-wide logging. The...

Use as_file for a package resource path

A Traversable package resource can be read directly with methods such as read_text() , but some APIs accept only a real pathlib.Path . importlib.resources.as_file() bridges that gap. Give it a Traversable , normally obtained from files(package).joinpath(name) , and use the resulting path inside a with statement. The temporary package in this example contains message.txt with the text hello . files(package).joinpath("message.txt") identifies that resource without assuming an installation directory. Within as_file(resource) , the code asserts that the supplied object is a file, reads its UTF-8 content through the provided Path , and prints message.txt: hello . The post-context assertion preserves the value read while ensuring the output does not depend on a machine-specific temporary location. A resource may already be a normal file, as it is in this fixture, or it may need extraction before a filesystem-only consumer can use it. When extraction is needed, as_file() cle...

Ignore HTML comments while collecting links

HTML comments can contain text that resembles markup, including old links or disabled snippets. A callback parser avoids treating that text as live markup. In this example, handle_starttag() accepts only a elements and turns the attribute-pair list into a dictionary before reading href . handle_comment() records the comment for the assertion but intentionally does not parse its contents or add an address. The fixture has two actual anchors and one comment containing a third, fake anchor. The exact output contains only /guide and /contact ; the assertion also demonstrates that the comment callback received the expected comment body. HTMLParser calls handle_comment() for comment markup, whereas start-tag callbacks are reserved for actual tags it recognizes in the input stream. This does not validate the links or resolve relative URLs. It also does not make arbitrary broken HTML equivalent to browser DOM parsing: HTMLParser is tolerant of invalid markup but does not check that st...

Strip a UTF-8 byte-order mark from a fixture

A UTF-8 byte-order mark is sometimes present at the beginning of exported fixtures. If ordinary utf-8 decoding reads those leading bytes, the resulting text begins with U+FEFF. For a fixture format that permits a UTF-8 signature but expects ordinary text content, read it with the utf-8-sig codec instead. On decoding, that codec skips the three BOM bytes only when they occur at the start of the file. The example creates an isolated temporary directory and writes known bytes: the UTF-8 BOM followed by a UTF-8 encoded title. Path.read_text(encoding="utf-8-sig") returns the title and newline without a leading U+FEFF. The assertions check both the exact decoded content and the absence of that leading character. The program then prints the fixture text exactly. Do not apply this choice blindly to arbitrary data. A leading U+FEFF can be intentional content, and utf-8-sig does not detect or fix a different encoding or malformed UTF-8; normal decoding errors still need a deliber...

Split a colon-delimited local setting once

A colon-delimited setting should usually be separated at its first delimiter, not at every colon in the value. The literal setting in this example is endpoint:https://example.test:8443/api . Calling split(":", 1) produces exactly two strings: endpoint and https://example.test:8443/api . The delimiter is removed from the returned fields. The maximum-split argument of 1 preserves both the scheme colon and port colon in the value. The assertion checks the pair before a formatted line presents the concrete result. str.split(sep, maxsplit) is a standard Python string method. With an explicit separator, it divides the string at that delimiter; consecutive separators can produce empty fields. Here, the first colon is the divider and the rest of the value remains opaque. The official built-in types documentation for str.split specifies that at most maxsplit splits occur. This API is available in Python 3 and has no newer-version requirement. This pattern is appropriate only w...

Parse a small XML settings fixture

For a compact, controlled XML fixture, xml.etree.ElementTree.fromstring() parses a string directly into its root Element . This example keeps the settings document in memory, finds its direct setting children, and constructs a dictionary from each name attribute and text value. The assertions check the root tag, both decoded settings, and the printed output order. The fixture represents a small application configuration: theme has the value dark , and retries has the value 3 . The list comprehension follows source order, which makes the output deterministic after the dictionary’s insertion order is established. Element.get() retrieves the name attribute and Element.text exposes each element’s text content. The assertions verify this particular fixture and extraction logic; they do not validate a wider configuration schema. ElementTree is a straightforward tree API, but it is not a schema validator and its supported XPath syntax is intentionally limited. This snippet also ass...

Normalize line endings before a text comparison

Two text values may represent the same lines while differing byte-for-byte because one uses Windows CRLF line endings, another uses classic CR endings, and another uses LF. When the comparison rule considers those forms equivalent, normalize each value first. This example replaces CRLF with LF before replacing remaining CR characters. That order matters: replacing CR first would turn a CRLF pair into two LF characters. The left value contains all three common forms. After normalization it equals the right value, whose lines use LF. A second assertion verifies that applying the function to already-normalized text leaves this particular input unchanged. The output uses repr so the final newline and embedded newline characters are visible rather than rendered as line breaks. This function intentionally changes only newline representation. It does not remove a final newline, trim spaces, repair text decoding, or make all Unicode-equivalent strings compare equal. If those distinctions ma...

Decode HTML character references safely

HTML text often contains named references such as &amp; and &pound; , plus decimal or hexadecimal numeric references. html.unescape converts those references into Unicode characters using HTML 5 rules. In this example, it changes a pound reference, an ampersand reference, and the hexadecimal reference for a smiling face. The assertions verify the whole decoded result and a separate angle-bracket conversion before the program prints the exact string. This is a useful operation when the input is text known to contain HTML character references and the next step needs the readable characters. It is deterministic for the shown input and requires no network access or parser configuration. html.unescape was added in Python 3.4. “Safely” here means using the standard library’s defined HTML 5 reference-handling rules, not that the result is safe to render as HTML. Decoding &lt;tag&gt; produces <tag> ; if that text will be inserted into an HTML document, apply context...

Attach a named logger without configuring the root logger

A named logger can serve a single component without calling logging.basicConfig() or adding a handler to root. This example snapshots the root logger's handlers, creates the named logger service.worker , and attaches an in-memory StreamHandler only to that named logger. The handler's format is intentionally compact and uses a fixed warning message. propagate=False keeps this record from also being offered to root handlers. After logging retry=0 , the example asserts the exact text captured in its private StringIO and asserts that the root handler tuple is unchanged from the earlier snapshot. It then prints the captured line, producing WARNING service.worker retry=0 with one final newline. The assertion establishes only that this code did not change root handlers during this run. It does not configure root globally, silence other named loggers, or prove that another thread will not change logging configuration. In an application that can initialize the same component mor...