Reputation: 3649
I come across a long typing declaration in python 3.7.
name_list: List[Dict[str, Union[str, Any]]] = [
{"name": "name1", "endDate": "", "character": "good"
},
]
The typing declaration List[Dict[str, Union[str, Any]]]
looks long and inefficient. Is it correct in the first place and what does it mean exactly? Are there shorter ways to make the typing declaration in this context? For example, is List[Dict]
just as valid?
Upvotes: 0
Views: 163
Reputation: 20500
Please bear with me as I run through the general to the specific. :)
You are running into the need to describe your full data structure. This problem predates Python and is a will lead to you to people arguing philosophy. Many would argue the choice of data structures is fully half the design of the program, e.g., Wirth.
You are currently choosing between the value of catching an error in calling the program versus the cost of writing the typing declaration. You have three options:
Use no or less specific declarations. If you use List[Dict]
or just List
, you get some checking at the cost of documentation. This chooses using the type checker as a guide rather than an enforcer.
Set up your types as a variable, often with the documentation of any other constraints. This represents enforcing your types as code. Here is an example:
Interest_List_Type = List[Dict[str, Any]]
# Unique, sorted list of dictionaries. Dictionary keys are strings
# corresponding to the keys in the Interests table, with values being
# details. Some interests have none string entries.
interest_list: Interest_List_Type = [
{"Akido": "Black Belt",
"Reading": "Biographies"
},
]
Use the previous approach with more granularity. For example:
Interest_Type = Dict[str, Any]
# An interest dictionary. Each key corresponds to a key in the Interests
# database table. Most values are strings, though some are not; e.g.,
# "Furry" is a boolean. Keys are sorted.
Interest_List_Type = List[Interest_Type]
# Unique, sorted list of dictionaries used for clustering users.
User_Type = Dict[str: Union[Personal_Information_Type, Interest_Type, Stats_Type]]
# A single user record with three keys: "user", "interests", and "stats"
#
interest_list: Interest_List_Type = [
{"Akido": "Black Belt",
"Reading": "Biographies"
},
]
You should explicitly choose when to use and document data structures. They are often the hardest to comprehend aspect of maintaining and extending a program.
Keep hacking! Keep notes.
Upvotes: 3