Skip to content

Instantly share code, notes, and snippets.

@e-dreyer
Last active August 14, 2023 10:17
Show Gist options
  • Save e-dreyer/0414d91c2c42f0c7eb1fed6b5a33cd9f to your computer and use it in GitHub Desktop.
Save e-dreyer/0414d91c2c42f0c7eb1fed6b5a33cd9f to your computer and use it in GitHub Desktop.
Python nested TypedDict example for discuss.python.org
from typing_extensions import TypedDict
from typing import Optional
class NodeDict(TypedDict):
id: str
value: int
parent: Optional['NodeDict'] # No error anymore
parent_node = NodeDict(
id='parent_node_id',
value=1,
parent=None
)
child_node = NodeDict(
id='child_node_id',
value=0,
parent=parent_node
)
from typing import TypedDict
NodeDict = TypedDict('NodeDict', {
'id': str,
'value': int,
'parent': None | 'NodeDict' # Error occurs here
})
new_node = NodeDict(
id='my_id',
value=0,
parent=None
)
@e-dreyer
Copy link
Author

Python Discuss topic regarding this snippet

@e-dreyer
Copy link
Author

The solution was found by me during the discussion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment