QA
Intermediate LevelPython

How do advanced typing constructs (Union, Optional, Literal, Annotated, TypeGuard) enhance static code analysis?

❓ Interview Prompt: Explain advanced type hints: `Union` (`int | str`), `Optional`, `Literal` (fixed string values), `Annotated` (attaching metadata), and `TypeGuard`.

Modern Python 3.10+ typing provides powerful static analysis annotations:

•
'Union[int, str]' or 'int | str': Value can be integer OR string.
•
'Literal['admin', 'user']': Restricts parameters to exact literal string values.
•
'Annotated[int, Field(...)]': Attaches metadata to types (consumed by Pydantic and FastAPI!).

Code Implementation Example

python
from typing import Literal, Annotated

# Restrict role parameter to exact literal choices
RoleType = Literal['ADMIN', 'MEMBER', 'GUEST']

def set_user_role(user_id: int, role: RoleType) -> None:
    print(f'User {user_id} assigned role: {role}')

set_user_role(101, 'ADMIN')
# mypy catches invalid literals like set_user_role(101, 'SUPERUSER')!
💡Restricting parameter values using typing.Literal type annotations.
🎯 Interview Key Takeaway

Use Literal type hints to restrict function parameters to exact allowable string options.

#typing#Literal#Annotated#Type Hints#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?