Can I use experimental types from typing_extensions?

Viewed 1088

To be more specific:

To solve questions like How do I type hint a method with the type of the enclosing class?
PEP 673 introduces typing.Self. The PEP is a Draft, but it currently an experimental type in typing_extensions 4.0.0

I tried using this in python 3.8

@dataclasses.dataclass
class MenuItem:
    url: str
    title: str
    description: str = ""
    items: typing.List[typing_extensions.Self] = dataclasses.field(default_factory=list)

But it raises

TypeError: Plain typing_extensions.Self is not valid as type argument

I could just use the literal string "MenuItem" instead. But I was wondering why this doesn't work.

1 Answers

Yes you can, but be aware of the uses of the package:

The typing_extensions module serves two related purposes:

  • Enable use of new type system features on older Python versions. For example, typing.TypeGuard is new in Python 3.10, but typing_extensions allows users on previous Python versions to use it too.
  • Enable experimentation with new type system PEPs before they are accepted and added to the typing module.

This specific case was a bug in typing_extensions. It's being planned to get fixed in 4.0.1.

Related