Skip to content

Methods with the same name as a type sometimes cause error "not valid as a type" #15047

@tilsche

Description

@tilsche

Bug Report

When using a decorator on a class method with the same name as a type used in its return type, and the method is decorated with a decorator that spans multiple lines, an error is thrown.

What puzzles me is that this only causes an error if the decorator spans multiple lines, not if it is just on a single line.

Neither pylint nur flake8 do complain about having a method that shadows another name in general. So I am assuming that this should be generally ok.

To Reproduce

class Foo:
    @property
    # the existence of this comment triggers the error
    def int(self) -> int:
        return 0

Some more examples show that this

  • The error occurs in any situation where the decorator starts more than one line before the function definition.
    • with a blank line in between
    • with a comment line in between
    • with a multi-line argument decorator (this is the case where I initially encountered it when using @deprecated.
  • The error occurs with both built-in decorators (@property) and custom defined decorators.
  • The error occurs both with built-in types and imported types.

Expected Behavior

Use the types from the outer scope to construct the return type and validate correctly.

Actual Behavior

error: Function "__main__.Foo.int" is not valid as a type  [valid-type]
note: Perhaps you need "Callable[...]" or a callback protocol?

Your Environment

  • Mypy version used: 1.2.0, master branch via mypy-play.net
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10 and 3.11 tested

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