Correct scoping of class type in TypedDict subclass

Hi folks,

I’m attempting to build an API helper class as part of a monolith utility script. Within said class, I have defined both a custom-type to be used in the class as well as a TypedDict subclass.

The problem is that I’m not sure what the proper method would be to define an attribute of the TypedDict (abc_code) with the custom type defined earlier in the (parent) class. Running my current code returns the error NameError: name 'ApplicationAPI' is not defined but, interestingly enough, my IDE (PyCharm) indicates no problems.

I’m aware that I could hoist my custom type outside of the ApplicationAPI class, but I feel that doing so would diminish the structure of my script. What other options do I have in applying this type?

from typing import Literal, TypeAlias, TypedDict, Unpack, cast, NotRequired, Required, Optional
from decimal import Decimal

#...

class ApplicationAPI:
    type ABC_Code = Literal['A', 'B', 'C', None]

    class PartMasterInstance(TypedDict):
        part_number: Required[str]
        part_revision: Required[str]
        standard_material_cost: NotRequired[Decimal]
        rolled_material_cost: NotRequired[Decimal]
        minimum_order_quantity: NotRequired[Decimal]
        abc_code: NotRequired[ApplicationAPI.ABC_Code]
        lead_time: NotRequired[Decimal]
        item_memo: NotRequired[str]

What goes wrong with this:?

class ApplicationAPI:
    type ABC_Code = Literal['A', 'B', 'C', None]

    class PartMasterInstance(TypedDict):
        ...
        abc_code: NotRequired[ABC_Code]
1 Like

Removing the scope prefix results in the error: NameError: name ‘ABC_Code’ is not defined

Oh, so it does. Sorry!

I don’t get such an error with the following, though:

from __future__ import annotations

from typing import Literal, NotRequired, TypedDict

class ApplicationAPI:
    type ABC_Code = Literal['A', 'B', 'C', None]

    class PartMasterInstance(TypedDict):
        abc_code: NotRequired[ABC_Code]
1 Like

Thank you! Importing annotations resolved the issue

1 Like

Is there a good reason for you to nest the class? There is rarely any good use case for a nested class in Python. It also brings headaches from the inability for the inner class to reference names defined in the outer class that you are experiencing because the outer class isn’t yet defined while the inner class is being defined.