Python <3.9 Syntax for Inheriting Generic Type

I’m using Python 3.8, and I’ve seen:

What is the syntax for defining a class that inherits from a Generic type?

I’ve tried the following:

# Python 3.8
from __future__ import annotations

from collections import OrderedDict
from typing_extensions import TypeAlias

od_alias: TypeAlias = 'OrderedDict[str, int]'

class mydict(OrderedDict[str, int]):  # Subscript for class "OrderedDict" will generate runtime exception; enclose type annotation in quotes
    pass

class mydict(OrderedDict['str', 'int']):  # Subscript for class "OrderedDict" will generate runtime exception; enclose type annotation in quotes
    pass

class mydict(od_alias):  # Inheriting 'od_alias', which is not a class
    pass

Use typing.OrderedDict instead of collections.OrderedDict.

from typing import OrderedDict

class MyDict(OrderedDict[str, int]):
    pass
3 Likes

Oh doy! I forgot that from __future__ import annotations doesn’t cover me in this case for <3.9. Thank you!

Yeah, that future import only helps with annotations, not anywhere else. The base class in a class definition is not an annotation, neither is anything to the right of equals sign in a TypeAlias declaration (that is another common case which people forget when using that future import).

1 Like