1. Dictionaries vs. TypedDicts
Regular Dictionary π
A standard Python dictionary allows any keys and values without enforcing any rules.- Pros: Flexible and fast.
- Cons: No type safety. The code does not check if key names are spelled correctly or if values are of the correct type, leading to potential runtime crashes.
Typed Dictionary β¨
ATypedDict allows us to define a dictionary with a fixed set of keys and specific types for each key. This is the primary way we define Graph States in LangGraph.
- Pros: Explicit, self-documenting, and validated by static analysis tools (like Ruff or Pyright) to catch bugs early.
2. Union Type π€
AUnion indicates that a variable can hold one of several specified types.
π‘ Note: In Python 3.10+, you can writeint | floatinstead ofUnion[int, float].
3. Optional Type π€
AnOptional type specifies that a variable can either be of a specific type, or None. It is shorthand for Union[Type, None].
4. Any Type π²
Any is a special type that matches any and all types. It turns off type checking for that variable.
- Use
Anysparingly, as it bypasses the safety benefits of type checking.
5. Lambda Functions β³
A lambda function is a small, anonymous function defined in a single line using thelambda keyword. In LangGraph, we often use lambdas as simple passthrough nodes or quick routers.