Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The wildcard pattern, represented by an underscore (_), is an irrefutable pattern in Python’s structural pattern matching (introduced in Python 3.10 via PEP 634). It successfully matches any subject value but explicitly drops the value without binding it to a variable name in the local scope.

Syntax and Mechanics

The wildcard pattern can be utilized as a standalone catch-all clause or nested within more complex structural patterns (such as sequences, mappings, or class patterns) to ignore specific elements.
match subject:
    case _:
        # Standalone wildcard: Matches any subject unconditionally
        pass
match sequence_subject:
    case [first, _, third]:
        # Nested wildcard: Matches a 3-element sequence, ignoring the second element
        pass
    case [first, *_, last]:
        # Starred wildcard: Matches a sequence of >=2 elements, ignoring the middle
        pass

Technical Characteristics

1. Irrefutability and Ordering Because the wildcard pattern is irrefutable (it never fails to match), a standalone case _: must be the final case block in a match statement if multiple cases are defined. The Python parser enforces this strictly; placing any case block after a top-level wildcard pattern raises a SyntaxError: wildcard makes remaining patterns unreachable. 2. Non-Binding Nature Unlike a capture pattern (e.g., case x:), the wildcard pattern does not assign the matched subject to the identifier _. If you attempt to reference _ within the execution block of the case, it will not contain the matched value. Instead, it will resolve to whatever _ evaluates to in the enclosing scope (which may result in a NameError if unbound). 3. Multiplicity in Structural Patterns Python’s pattern matching rules dictate that a variable name cannot be bound more than once in a single pattern (e.g., case [x, x]: raises a SyntaxError). However, because the wildcard pattern does not bind values, it is exempt from this restriction. It can be repeated infinitely within a single structural pattern.
match subject:
    # Valid: Multiple wildcards in a single pattern
    case [_, _, _]: 
        pass
    
    # Valid: Wildcards in mapping patterns
    case {"name": _, "age": _}:
        pass
4. Soft Keyword Context The underscore _ acts as a wildcard pattern only within the context of a match/case block. Outside of structural pattern matching, _ remains a standard, valid identifier in Python, commonly used by convention to denote unused variables in assignments or loops.
Master Python with Deep Grasping Methodology!Learn More