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.”1
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.2 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.
Footnotes
-
In Python, “types” and “classes” effectively refer to the same thing, so
object
refers both to Python’s base class and base type. ↩ -
Many thanks to these helpful Reddit commenters who taught me about
object
after I shared my previous workaround of hacking generics to replicate “unknown” in Python. ↩