python / python/mypy

(🐞) `type.__call__` not checked properly

Open
#17,316 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

class A:
    def __init__(self, x: int):
        print(x)

A.__call__("a")  # no error
A("a")  # Argument 1 to "A" has incompatible type "str"; expected "int"  [arg-type]

The typing spec says:

At runtime, a call to a class’ constructor typically results in the invocation of three methods in the following order:

  1. The __call__ method of the metaclass (which is typically supplied by the type class but can be overridden by a custom metaclass and which is responsible for calling the next two methods)

So mypy is checking that usages of the call syntax (()) are conforming to the constructor type, but the functionally identical call attribute __call__. This is against the spec, which specifies that type checkers should mirror the behavior that __call__ will invoke __new__ and __init__

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with mypy's handling of constructor calls and attribute calls to type.__call__, using the example in the issue as the reproduction. Trace how A("a") is checked versus A.__call__("a"), then add coverage showing that both forms enforce the constructor argument type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.