Inconsistency with NewType

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

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
compilers

Research direction

Start by reproducing the supplied NewType example and compare mypy's accepted operations with Python's runtime behavior. Trace the existing NewType handling and determine the intended boundary between calling a NewType and using it in an annotation; the issue needs a precise completion criterion and related tests before implementation can begin.

Written by the indexing model from the issue text.

Description

topic-newtype topic-runtime-semantics

This passes a type check:

from typing import NewType
class C:
    @classmethod
    def foo(cls) -> int: pass
D = NewType('D', C)
D.foo()  # Runtime error here (line 5)

But it fails at runtime, like this:

Traceback (most recent call last):
  File "_.py", line 6, in <module>
    D.foo()
AttributeError: 'function' object has no attribute 'foo'

This is because at runtime D is just a function (the identity function, to be clear) but mypy type-checks the program assuming it is a subclass of C.

Perhaps we can keep track of the status of D as a NewType and ensure that nothing is done to it except calling it (or using it in an annotation)?

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.