> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Essentials

> Master the Python type annotations and concepts required to build LangGraph states

To write code in LangGraph, you need a good understanding of Python's type hinting system. Because LangGraph passes a shared State around, we must precisely annotate what kinds of data are allowed inside our State.

## 1. Dictionaries vs. TypedDicts

### Regular Dictionary 📖

A standard Python dictionary allows any keys and values without enforcing any rules.

```python theme={null}
movie = {"name": "Avengers Endgame", "year": 2019}
```

* **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 ⌨

A `TypedDict` 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**.

```python theme={null}
from typing import TypedDict

class Movie(TypedDict):
    name: str
    year: int

# Correct usage
movie = Movie(name="Avengers Endgame", year=2019)

# Type checker will flag this because 'year' must be an integer:
# movie = Movie(name="Iron Man", year="2008")
```

* **Pros**: Explicit, self-documenting, and validated by static analysis tools (like Ruff or Pyright) to catch bugs early.

## 2. Union Type 🤝

A `Union` indicates that a variable can hold one of several specified types.

```python theme={null}
from typing import Union

# x can be either an int or a float
def square(x: Union[int, float]) -> float:
    return x * x

x = 5       # Valid
x = 1.234   # Valid
# x = "text"  # Invalid (type checker will flag this)
```

> 💡 **Note**: In Python 3.10+, you can write `int | float` instead of `Union[int, float]`.

## 3. Optional Type 🤔

An `Optional` type specifies that a variable can either be of a specific type, or `None`. It is shorthand for `Union[Type, None]`.

```python theme={null}
from typing import Optional

def nice_message(name: Optional[str] = None) -> None:
    if name is None:
        print("Hey random person!")
    else:
        print(f"Hi there, {name}!")
```

## 4. Any Type 🎲

`Any` is a special type that matches any and all types. It turns off type checking for that variable.

```python theme={null}
from typing import Any

def print_value(x: Any):
    print(x)

print_value(123)
print_value("Batman")
```

* Use `Any` sparingly, 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 the `lambda` keyword. In LangGraph, we often use lambdas as simple passthrough nodes or quick routers.

```python theme={null}
# A lambda function that squares a number
square = lambda x: x * x
print(square(10)) # Output: 100

# Used with map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
# squares is [1, 4, 9, 16]
```
