When processing template strings introduced in PEP 750, using isinstance() checks to handle different types of template components
results in verbose and less readable code. PEP 750 specifically recommends using structural pattern matching as the best practice for template
processing.
Structural pattern matching with match/case statements provides several advantages:
- Better readability: The pattern matching syntax is more concise and expressive than multiple
isinstance() checks
- Follows PEP recommendations: PEP 750 explicitly recommends this approach as the expected best practice
- More Pythonic: Pattern matching is the modern Python way to handle type-based dispatching
What is the potential impact?
Using isinstance() checks instead of structural pattern matching when processing template strings results in more verbose, less
readable code that doesn’t follow the recommended patterns from PEP 750. While functionally equivalent, it makes the codebase harder to maintain and
understand.
Exceptions
This rule raises issues only on Python 3.14 code.
How to fix?
Replace isinstance() checks with structural pattern matching using match/case statements. Use type patterns
like str() and Interpolation() to handle different template components.
Non-compliant code example
def process_template(template):
result = []
for item in template:
if isinstance(item, str): # Noncompliant
result.append(item.lower())
elif isinstance(item, Interpolation): # Noncompliant
result.append(str(item.value).upper())
return ''.join(result)
Compliant code example
def process_template(template):
result = []
for item in template:
match item:
case str() as s:
result.append(s.lower())
case Interpolation() as interp:
result.append(str(interp.value).upper())
return ''.join(result)
Documentation