A literal pattern is a structural pattern matching construct in Python that evaluates whether a subject expression exactly matches a specified constant literal. Operating within aDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
match...case block, it acts as the simplest form of pattern matching, routing execution flow based on direct value equivalence.
Evaluation Mechanics
The underlying comparison mechanism depends on the type of literal provided in thecase clause:
- Equality (
==): For numbers (integers, floats, complex), strings, and bytes, Python evaluates the pattern using the equality operator. The match succeeds ifsubject == literal. - Identity (
is): For singletons (None,True, andFalse), Python strictly evaluates the pattern using the identity operator. The match succeeds only ifsubject is literal.
Syntax
Supported Literal Types
Literal patterns strictly accept the following built-in constant types:- Strings:
"text",'text',r"raw" - Bytes:
b"bytes" - Integers:
10,-5,0xFF - Floats:
3.14,1e10 - Complex Numbers:
3+4j - Booleans:
True,False - Null Object:
None
Technical Constraints and Nuances
1. F-Strings are Invalid Formatted string literals (f-strings) cannot be used as literal patterns. Because f-strings are evaluated dynamically at runtime, they violate the requirement that patterns must be static constants.case statement is interpreted by the parser as a Capture Pattern, which unconditionally binds the subject to that variable name rather than comparing their values.
==, they are subject to standard IEEE 754 precision limitations. A subject resulting from a mathematical operation (e.g., 0.1 + 0.2) will fail to match a literal pattern of case 0.3: due to floating-point representation errors.
Master Python with Deep Grasping Methodology!Learn More





