MCPcopy
hub / github.com/python/mypy / validate_and_transform_accessors

Method validate_and_transform_accessors

mypy/checkstrformat.py:616–672  ·  view source on GitHub ↗

Validate and transform (in-place) format field accessors. On error, report it and return False. The transformations include replacing the dummy variable with actual replacement expression and translating any name expressions in an index into strings, so that this will work:

(
        self,
        temp_ast: Expression,
        original_repl: Expression,
        spec: ConversionSpecifier,
        ctx: Context,
    )

Source from the content-addressed store, hash-verified

614 return temp_ast
615
616 def validate_and_transform_accessors(
617 self,
618 temp_ast: Expression,
619 original_repl: Expression,
620 spec: ConversionSpecifier,
621 ctx: Context,
622 ) -> bool:
623 """Validate and transform (in-place) format field accessors.
624
625 On error, report it and return False. The transformations include replacing the dummy
626 variable with actual replacement expression and translating any name expressions in an
627 index into strings, so that this will work:
628
629 class User(TypedDict):
630 name: str
631 id: int
632 u: User
633 '{[id]:d} -> {[name]}'.format(u)
634 """
635 if not isinstance(temp_ast, (MemberExpr, IndexExpr)):
636 self.msg.fail(
637 "Only index and member expressions are allowed in"
638 ' format field accessors; got "{}"'.format(spec.field),
639 ctx,
640 code=codes.STRING_FORMATTING,
641 )
642 return False
643 if isinstance(temp_ast, MemberExpr):
644 node = temp_ast.expr
645 else:
646 node = temp_ast.base
647 if not isinstance(temp_ast.index, (NameExpr, IntExpr)):
648 assert spec.key, "Call this method only after auto-generating keys!"
649 assert spec.field
650 self.msg.fail(
651 'Invalid index expression in format field accessor "{}"'.format(
652 spec.field[len(spec.key) :]
653 ),
654 ctx,
655 code=codes.STRING_FORMATTING,
656 )
657 return False
658 if isinstance(temp_ast.index, NameExpr):
659 temp_ast.index = StrExpr(temp_ast.index.name)
660 if isinstance(node, NameExpr) and node.name == DUMMY_FIELD_NAME:
661 # Replace it with the actual replacement expression.
662 assert isinstance(temp_ast, (IndexExpr, MemberExpr)) # XXX: this is redundant
663 if isinstance(temp_ast, IndexExpr):
664 temp_ast.base = original_repl
665 else:
666 temp_ast.expr = original_repl
667 return True
668 node.line = ctx.line
669 node.column = ctx.column
670 return self.validate_and_transform_accessors(
671 node, original_repl=original_repl, spec=spec, ctx=ctx
672 )
673

Callers 1

apply_field_accessorsMethod · 0.95

Calls 5

StrExprClass · 0.90
isinstanceFunction · 0.85
lenFunction · 0.85
failMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected