-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Generic NewType? #3331
Comments
Hm, that may actually be reasonable. After all NewType is an optimized version of subclassing that erases the distinction at runtime -- and generics are also erased at runtime, so that may be a reasonable match. |
Because of this, at runtime |
Ahh, I see. Could it not be done like:
Would that be such a large overhead? It seems like potentially it could be made somewhat opt-in. By that I mean that if you do |
That would parallel fairly reasonably with expectations people may have from similar behavior in other languages. Value types in scala are usually erased, for example, except in some cases. Similarly for newtypes in haskell, as I understand it. And with traits in rust. I don't think it's that bad of a drawback, considering that the drawback only occurs when supporting something that currently can't be done at all. As long as it's documented it seems reasonable, at least. |
Approximately 30x slower:
|
What about normal subclassing? Your example can be just this class SortedList(List[T]):
def __init__(self, lst: List[T]) -> None:
... |
Well, "not at all" is definitely an exaggeration. The drawback to the wrapper class is that I either have to implement proxy methods for every single list interface or expose a |
We have a slightly different use case for this. We want to be able to do:
Subclassing is not an option here due to the runtime overhead; these need to stay real ints at runtime. Without the generic, we either lose the ability to distinguish different types of IGIDs in the type system, or we have to create a separate type (e.g. This use case does require two new features: a) passing a tuple of types to @Daenyth it's not a wrapper class, it's a subclass, and the list constructor accepts a list already, so add a
The 30x overhead you timed would be paid only once per process, at
That's still probably enough of a cost that we will just go with the "lots of separate types" solution for our case instead. |
I'd also like to use generic from typing import NewType, List, NoReturn, TypeVar
ListOfInts = List[int]
NonEmptyListOfInts = NewType('NonEmptyListOfInts', ListOfInts)
def prove_sequence_of_ints_is_nonempty(seq: ListOfInts) -> NonEmptyListOfInts:
if len(seq) > 0:
return NonEmptyListOfInts(seq)
else:
raise ValueError('Sequence is empty')
def foo(seq: NonEmptyListOfInts) -> NoReturn: pass
a = [1, 2, 3]
b = prove_sequence_of_ints_is_nonempty(a)
foo(a) # Argument 1 to "foo" has incompatible type "List[int]"; expected "NonEmptyListOfInts"
foo(b) This mostly works as expected (except for methods mutating |
No update on this? I basically want to typehint multiprocessing queue which is probably impossible now? from logging import Handler
from multiprocessing import Queue as MPQueue
from queue import Queue
from typing import Union
DEFAULT_LIMIT = 10000
QueueValueType = Handler
QueueType = Queue[QueueValueType] # error here
ProcessQueueType = MPQueue[QueueValueType] # or here
QueueTypes = Union[QueueType, ProcessQueueType]
local_queue: QueueType = Queue(maxsize=DEFAULT_LIMIT)
process_queue: ProcessQueueType = MPQueue(maxsize=DEFAULT_LIMIT) is OK for mypy, but Python raises error
|
Hi @adaamz QueueType: TypeAlias = "Queue[QueueValueType]"
ProcessQueueType: TypeAlias = "MPQueue[QueueValueType]" might help. See https://peps.python.org/pep-0613/ |
This issue was opened many years ago. In recent versions T = TypeVar('T')
SortedList = NewType[T]('SortedList', list[T])
def my_sorted(items: list[T]) -> SortedList[T]:
return SortedList[T](sorted(items))
IGID = NewType[T]('IGID', int)
class User:
pass
user_id: IGID[User] = IGID(3) My proof-of-concept implementation is here. It can be copy-pasted into typing.py. @ilevkivskyi @JelleZijlstra What do you think? Does this need a PEP or can this be submitted as a PR? |
Not that I am final authority on this kind of questions, but I think this should probably be a PEP. Also PoC implementation should include not just |
This is necessary for newtyping existing instances of builtin Python types like |
I was thinking about the same thing ( |
Support for a generic |
Following the discussion here, I created a proposition in Python typing forum. |
Proper generic new subtypes of generics are not possible :( python/mypy#3331
I'd like to be able to write code like;
Currently I get
error: "SortedList" expects no type arguments, but 1 given
The text was updated successfully, but these errors were encountered: