Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Typing & static analysisSeniorOccasionalTheory

What is the difference between annotating something as `Any` versus `object`, even though both accept any value?

Answer

Both accept a value of literally any type, but they behave oppositely for a type checker afterward. `object` is the actual root of Python's type hierarchy, so a checker only lets you call methods that every object genuinely supports (like `__repr__`), and using it in a more specific context requires an explicit narrowing check first, such as `isinstance`. `Any` is a checker escape hatch that disables type checking entirely for that value: you can call any method, pass it anywhere, and the checker will not complain even if that operation would fail at runtime, which makes `Any` far less safe and something to use sparingly, typically only at real dynamic-data boundaries.

Strong answer includes

  • object is the real type-hierarchy root, only universally-supported operations allowed
  • Any disables type checking entirely for that value
  • Any should be used sparingly, only at genuine dynamic-data boundaries

Practical example

A checker flags

Python example
def f(x: object): x.upper()

as an error because not every `object` has

Python example
.upper()

, but silently accepts

Python example
def f(x: Any): x.upper()

even though passing an `int` at runtime would crash.

#typing#any#object

Sources

typing — Support for type hintsPython Software Foundation · Generics, protocols, overloads and typing-module semanticsPEP 484 — Type HintsPython Software Foundation · Foundational type-hint syntax and static-typing intent