Using "object" as an unknown type in Python
Updated 1 year ago
TypeScript has an unknown type, which can be quite useful. Python doesn't have "unknown", but its object type can be used the same way.
The object type
The object type in Python "is a base for all classes" containing the "methods that are common to all instances of Python classes." And since in Python "types" and "classes" are effectively the same thing, object is both Python's base class and base type.
While Python doesn't explicitly advertise object as the language's "use when you're not sure" type, it works well for that use case because it only includes the features all types share.¹ Beyond that, it makes no assumptions about what type features a value might have.
In practice, using the object type tells Mypy to warn you if you start making unvalidated assumptions about what you can safely do with that value:
def unsafe(value: object) -> None:
value.get("some_key")
# 🚨 "object" has no attribute "get"
To pass the type-checker, you need to confirm value has a get method before you use it:
def safe(value: object) -> None:
if not isinstance(value, dict):
return None
value.get("some_key")
# other logic...
You won't need object for data you create yourself, but it can make validating external data much safer and easier.