Any vs. object
The type object
is another type that can have an instance of arbitrarytype as a value. Unlike Any
, object
is an ordinary static type (itis similar to Object
in Java), and only operations valid for _all_types are accepted for object
values. These are all valid:
- def f(o: object) -> None:
- if o:
- print(o)
- print(isinstance(o, int))
- o = 2
- o = 'foo'
These are, however, flagged as errors, since not all objects support theseoperations:
- def f(o: object) -> None:
- o.foo() # Error!
- o + 2 # Error!
- open(o) # Error!
- n = 1 # type: int
- n = o # Error!
You can use cast()
(see chapter Casts and type assertions) or isinstance()
togo from a general type such as object
to a more specifictype (subtype) such as int
. cast()
is not needed withdynamically typed values (values with type Any
).