📄 Parent resource: My general Python notes
Resources
- One page cheatsheet
- https://github.com/microsoft/pyright/blob/main/docs/type-concepts.md
- Official PEPs
- PlainEnglish Python: Python for TypeScript Developers
- My docs: Using Python Type-Checking Features in VSCode
- Benita: Exhaustiveness Checking with Mypy
Strongly-Typed Dictionaries and Objects
Typed-Dicts
A TypedDict is really just a type-annotation layer over a standard dictionary.
Syntax:
from typing import TypedDict
# Class declaration
class Snack(TypedDict, total=True):
name: str
calories: int
apple: Snack = {
'name': 'Medium Apple',
'calories': 95
}
# Alternate syntax
Snack = TypedDict('Snack', {'name': str, 'calories': int}, total=True)
apple: Snack = {
'name': 'Medium Apple',
'calories': 95
}
Currently, inline / anonymous TypedDicts are not supported, although there is discussion around supporting them
There is are known issue (#10759 and #7981) with mypy and
TypedDict.values()
returning the wrong types
Miscellaneous Questions and TypeScript Equivalents
NotRequired[T]
vsOptional[T]
?NotRequired[T]
can be used to mark a property as being completely optionalOptional[T]
means the property is still required, but can beNone
(type isT | None
/Union[T, None]
)
- Null or undefined types?
- Python uses
None
instead ofNull
orUndefined
. - Typing a possibly unset variable?
- Although you can use
possible_string: Union[None, other_type]
to represent the type ofNone | other_type
, a shorter way is withOptional[other_type]
- Although you can use
- Checking for
None
?if my_var is None
or even justif not my_var
works for checking if variable ==None
, but not for checking if a variable exists period (this will throw an exception is variable is not defined)
- Python uses
- Equivalent to TS
ReturnType<T>
?- Does not exist - see issue #769
- Equivalent to TS
typeof {MY_VAR}
?- Nope, same as above
- Equivalent to
@ts-ignore
?# type: ignore
- If you get an Invalid "type: ignore" comment error, a possible cause is adding your own text after it. E.g.,
# type: ignore blah blah
- If you get an Invalid "type: ignore" comment error, a possible cause is adding your own text after it. E.g.,
- Equivalent to TS assertions (like
myVar as myType
)?- Most efficient:
myVar as myType
->typing.cast(my_type, my_var)
- Less efficient (but perhaps safer): Using
assert
- https://stackoverflow.com/a/57931741/11447682
- Most efficient:
- Why don't
if type()
checks narrow the type?- They can, depending on checker. Try using
isinstance()
to narrow instead though.
- They can, depending on checker. Try using
- Using
isinstance()
is not working for narrowing- Try different syntax approaches. E.g.,
if not isinstance(my_obj, MyClass):
instead ofif isinstance(my_obj, MyClass) is not True:
- Try different syntax approaches. E.g.,
Troubleshooting
A word of warning; stubs can (and often are) shipped separately from the actual library; for example, VSCode's pylance extension provides out-of-the-box type stubs for Django, but these might not match the actual version of Django you happen to have installed in your project!
- Intellisense isn't kicking in when adding elements in an array, dict, etc.
- Try adding a comma / separator before actually writing out the element. For some reason in VSCode, it won't work unless you do this when adding elements to a list.