Skip to content

Incorrect attribute access for functions nested inside methods #20479

Description

@bzoracler

Bug Report, To Reproduce, & Actual Behaviour

The first parameter of a function, nested inside a method, can inappropriately access certain attributes on the method's bound instance. See mypy Playground:

from typing_extensions import reveal_type

class A:
    class B: ...
    
    def method(self) -> None:
        def f2(arg: object) -> None:
            reveal_type(arg.B)  # N: Revealed type is "def () -> __main__.A.B"
        f2(3)  # Runtime error

The accessible items are static references to modules, classes, and type aliases. This is due to some implementation details in semanal.py:

mypy/mypy/semanal.py

Lines 6091 to 6097 in 30b2a2d

elif isinstance(base.node, Var) and self.type and self.function_stack:
# check for self.bar or cls.bar in method/classmethod
func_def = self.function_stack[-1]
if not func_def.is_static and isinstance(func_def.type, CallableType):
formal_arg = func_def.type.argument_by_name(base.node.name)
if formal_arg and formal_arg.pos == 0:
type_info = self.type

Expected Behavior

            reveal_type(arg.B)  # E: "object" has no attribute "B"  [attr-defined]

Your Environment

  • Mypy version used: 1.19.1, master

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions