python / python/mypy

Cannot combine NewType and Literal

Open
#9,650 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-literal-types topic-newtype
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

(This seems related to, but different from, #2448.)

Feature

Allow the creation of a NewType derived from Literal.

Pitch

Currently you can define the following types:

Foo = Literal["foo"]
Bar = NewType("Bar", str)

But you can't do this:

Baz = NewType("Baz", Foo)

If you attempt to, Python won't throw any error, but mypy will complain:

error: Argument 2 to NewType(...) must be subclassable

This prevents a strict definition of a literal-based type: you either have to accept all values of the literal's type or you need to lose the type check benefits of NewType.

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 by tracing how mypy validates NewType's second argument and how it represents Literal types, using the Baz = NewType("Baz", Foo) example and the reported subclassability error. Define the expected type-checking behavior for a NewType derived from Literal, then add coverage showing the accepted definition and its type-checking benefits.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
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.