1

Is there any way of parametrizing new types created with NewType, similar to how typing.Sequence and the like can be parametrized with subscripts? Or of achieving a similar result by different means?

The below example illustrates what I would like to do, but it fails with TypeError: 'function' object is not subscriptable, because NewType returns a function.

from typing import NewType, Sequence, TypeVar

T = TypeVar("T")
Type1 = NewType("Type1", float)
Type2 = NewType("Type2", Sequence[T])

Works = Sequence[Type1]
Fails = Type2[Type1]

The reason that I hoped to do this is that I am creating a dataclass where, in __post_init__, I would like to run some specific logic depending on the type of the attribute.

msailor
  • 340
  • 1
  • 8
  • Does this answer your question? [How to override the \[\] operator in Python?](https://stackoverflow.com/questions/1957780/how-to-override-the-operator-in-python) – mkrieger1 Jul 02 '21 at 14:34
  • @mkrieger1 Thanks! But the core of my question isn't about how to implement subscripting, but about how to parametrize custom types. I have edited the question to try to make this clearer. – msailor Jul 02 '21 at 15:25

2 Answers2

0

Type1 and Type2 are of type function which is not subscriptable. Even if you manually implement __getitem__ (the builtin function for the square bracket [] operator) on Type2 python will raise a TypeError.

If you really want to use square brackets on your type I recommend creating a class and implement __getitem__ and __setitem__.

Here is a simple example of what the class might look like:

class Foo:
    def __init__(self):
        self.__type_lookup = {}

    def __getitem__(self, key):
        return self.__type_lookup[key]
    
    def __setitem__(self, key, value):
        self.__type_lookup[key] = value
bpmason1
  • 1,900
  • 1
  • 12
  • 9
  • Thanks for the response! But I am hoping to stick with the objects provided by the standard library's `typing` module. I'd rather avoid creating a new class and having to reinvent the wheel vis-a-vis type checking etc. – msailor Jul 02 '21 at 15:19
  • I think the emphasis on subscripting in my question was perhaps a mistake; what I am really asking is how one can parametrize a type created with `NewType` that features `TypeVar`. I will edit the question to clarify. – msailor Jul 02 '21 at 15:21
  • If you're concerned about type checking then you can do that with the `isinstance` builtin. – bpmason1 Jul 02 '21 at 15:57
0

I found a solution in the section on generics in the Mypy docs: subclass the appropriate type from the typing module. (Rather than trying to use NewType.) For example,

from typing import NewType, Sequence

Type1 = NewType("Type1", float)

class Type2(Sequence):
    pass

Works = Type2[Type1]
msailor
  • 340
  • 1
  • 8