Choose Any or object at Unknown Boundaries
Core idea
object is a broad static type: any ordinary Python value can be assigned to it, but a checker requires narrowing before type-specific operations. Any opts out of much static checking and can hide mistakes as values flow through code. Prefer object for genuinely unknown inputs that will be validated.
def clean(value: object) -> str: if isinstance(value, str): return value.strip() return 'invalid'print(clean(' A '))print(clean(12))The runtime check also supplies a static narrowing condition.
Any does not convert values
from typing import Anydef raw(value: Any) -> Any: return valueresult = raw(12)print(type(result).__name__, result)Any changes the static contract, not the underlying object.
Common mistake
Do not use Any merely to silence a valid diagnostic. An operation accepted statically through Any can still fail at runtime.
Practice
Accept object and return the length of a string only after narrowing; choose a separate result for other inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Any and object
Check your understanding of any and object.
What is printed?
def f(x: object) -> bool: return isinstance(x, str)print(f(3))What is printed?
from typing import Anyx: Any = [1, 2]print(type(x).__name__)Which encourages explicit narrowing for unknown data?
What is a risk of Any?