Methods with the same name as a type sometimes cause error "not valid as a type"
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the minimal Python example in the report and run mypy 1.2.0 or current master, then compare a single-line decorator with versions separated by a comment, blank line, or multiline arguments. Trace how the method name is resolved while its return annotation is checked. Done means all shown decorator layouts accept the outer-scope type without the valid-type error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100