Joshua's Docs - Python Types - Resources, Notes, and Tips
Light

📄 Parent resource: My general Python notes

Resources

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] vs Optional[T]?
    • NotRequired[T] can be used to mark a property as being completely optional
    • Optional[T] means the property is still required, but can be None (type is T | None / Union[T, None])
  • Null or undefined types?
    • Python uses None instead of Null or Undefined.
    • Typing a possibly unset variable?
      • Although you can use possible_string: Union[None, other_type] to represent the type of None | other_type, a shorter way is with Optional[other_type]
    • Checking for None?
      • if my_var is None or even just if 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)
  • Equivalent to TS ReturnType<T>?
  • Equivalent to TS typeof {MY_VAR}?
  • 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
  • Equivalent to TS assertions (like myVar as myType)?
  • Why don't if type() checks narrow the type?
    • They can, depending on checker. Try using isinstance() to narrow instead though.
  • Using isinstance() is not working for narrowing
    • Try different syntax approaches. E.g., if not isinstance(my_obj, MyClass): instead of if isinstance(my_obj, MyClass) is not True:

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.
Markdown Source Last Updated:
Sun Feb 05 2023 01:27:47 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Sat Aug 06 2022 12:32:20 GMT+0000 (Coordinated Universal Time)
© 2023 Joshua Tzucker, Built with Gatsby
Feedback