I'm referring to the documentation available here to understand how the return types are defined while using function annotations.
I couldn't understand what the str in Dict[str, Any] refers to. Does str refer to the dictionary's keys and Any (meaning, it can be a string or an int) refer to the type of the dictionary's value?
EDIT:
In the above-mentioned link, it is mentioned
The PEP 484 type Dict[str, Any] would be suitable, but it is too lenient, as arbitrary string keys can be used, and arbitrary values are valid.
Could someone explain what does arbitrary string keys refer to? I understand keys are strings, but when we say arbitrary string keys do we just mean that the dictionary can take any key that is a string? Or does the word arbitrary hold any other significance here?
Yep! Normally python variables are mutable (types can change), but specifying it like this is good documentation and makes it very clear what goes where.
More usage documentation can be found here! https://docs.python.org/3/library/typing.html
The PEP documentation you refer to identifies how type-hints, albeit useful, are still error prone.
By specifying Dict[str, Any], the str can be "arbitrary", meaning it can be a string key of anything (ie. name, age, height, humidity). Out of these keys, one may consider "humidity" shouldn't be one of the string-keys for this dict, but there isn't a way to check, or enforce that until some error occurs down the road (hence, it is "arbitrary"; no rules to govern what are "allowed" string-keys of this dict).
Therefore, per the documentation, specifying this class (derived from TypedDict):
class Movie(TypedDict): name: str year: int
will specifically limit users to create a new kind of dict (a TypedDict) with string-keys name and year (with respective values typed str and int). Users will not be able to "arbitrarily" add a new key (ie. humidity) to this "Movie" TypedDict, or otherwise assign a non-int value to Movie["year"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With