Remix.run Logo
aSanchezStern 7 months ago

The thing that the author says they would prefer is already in Python, it's called NewType (https://docs.python.org/3/library/typing.html#typing.NewType)

They say "...so I can't create a bunch of different names for eg typing.Any and then expect type checkers to complain if I mix them."

`MyType = NewType('MyType', Any)`

is how you do this.

At the end, they suggest a workflow: "I think my ideal type hint situation would be if I could create distinct but otherwise unconstrained types for things like function arguments and function returns, have mypy or other typing tools complain when I mixed them, and then later go back to fill in the concrete implementation details of each type hint"

That's just doing the above, but then changing the `NewType('MyType', Any)` to something like `NewType('MyType', list[dict[str, int]])` later when you want to fill in the concrete implementation.

stavros 7 months ago | parent | next [-]

This is great, thank you for this. I've always wanted something that would complain if I passed Meters to something expecting Feet, but aliases didn't consider this an error.

cmcconomy 7 months ago | parent [-]

You should look into the pint library if you want full unit support!

stavros 7 months ago | parent [-]

That looks really useful, thank you! I don't always specifically want units, but it'll be great for when I do!

thatcks 7 months ago | parent | prev | next [-]

mypy sadly doesn't accept 'NewType('MyType', Any)'; it complains 'error: Argument 2 to NewType(...) must be subclassable (got "Any") [valid-newtype]'. Possibly this is allowed by other Python type checkers. It is accepted at runtime, and I wish mypy allowed Any as a specific exemption to its checks.

(I'm the author of the linked-to article.)

Der_Einzige 7 months ago | parent | prev [-]

Why is it that many of the examples for the "typing.protocal" class right below this involve meth??? Python WTF?

Hackbraten 7 months ago | parent | next [-]

`meth` is just a historical abbreviation.

Mind that support for methods as first-class objects was introduced with Python 2.5 [0].

That was in 2006, a few years before "meth" became engrained in European popular culture as an abbreviation for methamphetamines. The abbreviation was never changed.

[0]: https://docs.python.org/release/2.5/lib/typesmethods.html

kstrauser 7 months ago | parent | prev | next [-]

It’s a high level language.

rnewme 7 months ago | parent | prev [-]

method? Or are you being sarcastic?