This rule raises an issue when isinstance() checks are used to differentiate between string parts and Interpolation
objects while processing template strings, instead of using structural pattern matching with match/case statements.
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:
isinstance() checks
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.
This rule raises issues only on Python 3.14 code.
Replace isinstance() checks with structural pattern matching using match/case statements. Use type patterns
like str() and Interpolation() to handle different template components.
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)
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)