Yes, there is a difference. Although in Python 3, all objects are instances of object, including object itself, only Any documents that the return value should be disregarded by the typechecker.
The Any type docstring states that object is a subclass of Any and vice-versa:
>>> import typing
>>> print(typing.Any.__doc__)
Special type indicating an unconstrained type.
- Any object is an instance of Any.
- Any class is a subclass of Any.
- As a special case, Any and object are subclasses of each other.
However, a proper typechecker (one that goes beyond isinstance() checks, and which inspects how the object is actually used in the function) can readily object to object where Any is always accepted.
From the Any type documentation:
Notice that no typechecking is performed when assigning a value of type
Anyto a more precise type.
and
Contrast the behavior of
Anywith the behavior ofobject. Similar toAny, every type is a subtype ofobject. However, unlikeAny, the reverse is not true: object is not a subtype of every other type.That means when the type of a value is
object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error.
and from the mypy documentation section Any vs. object:
The type
objectis another type that can have an instance of arbitrary type as a value. UnlikeAny,objectis an ordinary static type (it is similar toObjectin Java), and only operations valid for all types are accepted for object values.
object can be cast to a more specific type, while Any really means anything goes and a type checker disengages from any use of the object (even if you later assign such an object to a name that is typechecked).
You already painted your function into a an un-typed corner by accepting list, which comes down to being the same thing as List[Any]. The typechecker disengaged there and the return value no longer matters, but since your function accepts a list containing Any objects, the proper return value would be Any here.
To properly participate in type-checked code, you need to mark your input as List[T] (a genericly typed container) for a typechecker to then be able to care about the return value. Which in your case would be T since you are retrieving a value from the list. Create T from a TypeVar:
from typing import TypeVar, List
T = TypeVar('T')
def get_item(L: List[T], i: int) -> T:
return L[i]
or, using Python 3.12 or newer:
def get_itemT -> T:
return L[i]
Answer from Martijn Pieters on Stack OverflowYes, there is a difference. Although in Python 3, all objects are instances of object, including object itself, only Any documents that the return value should be disregarded by the typechecker.
The Any type docstring states that object is a subclass of Any and vice-versa:
>>> import typing
>>> print(typing.Any.__doc__)
Special type indicating an unconstrained type.
- Any object is an instance of Any.
- Any class is a subclass of Any.
- As a special case, Any and object are subclasses of each other.
However, a proper typechecker (one that goes beyond isinstance() checks, and which inspects how the object is actually used in the function) can readily object to object where Any is always accepted.
From the Any type documentation:
Notice that no typechecking is performed when assigning a value of type
Anyto a more precise type.
and
Contrast the behavior of
Anywith the behavior ofobject. Similar toAny, every type is a subtype ofobject. However, unlikeAny, the reverse is not true: object is not a subtype of every other type.That means when the type of a value is
object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error.
and from the mypy documentation section Any vs. object:
The type
objectis another type that can have an instance of arbitrary type as a value. UnlikeAny,objectis an ordinary static type (it is similar toObjectin Java), and only operations valid for all types are accepted for object values.
object can be cast to a more specific type, while Any really means anything goes and a type checker disengages from any use of the object (even if you later assign such an object to a name that is typechecked).
You already painted your function into a an un-typed corner by accepting list, which comes down to being the same thing as List[Any]. The typechecker disengaged there and the return value no longer matters, but since your function accepts a list containing Any objects, the proper return value would be Any here.
To properly participate in type-checked code, you need to mark your input as List[T] (a genericly typed container) for a typechecker to then be able to care about the return value. Which in your case would be T since you are retrieving a value from the list. Create T from a TypeVar:
from typing import TypeVar, List
T = TypeVar('T')
def get_item(L: List[T], i: int) -> T:
return L[i]
or, using Python 3.12 or newer:
def get_itemT -> T:
return L[i]
Any and object are superficially similar, but in fact are entirely opposite in meaning.
object is the root of Python's metaclass hierarchy. Every single class inherits from object. That means that object is in a certain sense the most restrictive type you can give values. If you have a value of type object, the only methods you are permitted to call are ones that are a part of every single object. For example:
foo: object = 3
# Error, not all objects have a method 'hello'
bar = foo.hello()
# OK, all objects have a __str__ method
print(str(foo))
In contrast, Any is an escape hatch meant to allow you to mix together dynamic and statically typed code. Any is the least restrictive type -- any possible method or operation is permitted on a value of type Any. For example:
from typing import Any
foo: Any = 3
# OK, foo could be any type, and that type might have a 'hello' method
# Since we have no idea what hello() is, `bar` will also have a type of Any
bar = foo.hello()
# Ok, for similar reasons
print(str(foo))
You should generally try and use Any only for cases where...
- As a way of mixing together dynamic and statically typed code. For example, if you have many dynamic and complex functions, and don't have time to fully statically type all of them, you could settle for just giving them a return type of Any to nominally bring them into the typechecked work. (Or to put it another way, Any is a useful tool for helping migrate an untypechecked codebase to a typed codebase in stages).
- As a way of giving a type to an expression that is difficult to type. For example, Python's type annotations currently do not support recursive types, which makes typing things like arbitrary JSON dicts difficult. As a temporary measure, you might want to give your JSON dicts a type of
Dict[str, Any], which is a bit better then nothing.
In contrast, use object for cases where you want to indicate in a typesafe way that a value MUST literally work with any possible object in existence.
My recommendation is to avoid using Any except in cases where there is no alternative. Any is a concession -- a mechanism for allowing dynamism where we'd really rather live in a typesafe world.
For more information, see:
- https://docs.python.org/3/library/typing.html#the-any-type
- http://mypy.readthedocs.io/en/latest/kinds_of_types.html#the-any-type
For your particular example, I would use TypeVars, rather then either object or Any. What you want to do is to indicate that you want to return the type of whatever is contained within the list. If the list will always contain the same type (which is typically the case), you would want to do:
from typing import List, TypeVar
T = TypeVar('T')
def get_item(L: List[T], i: int) -> T:
return L[i]
This way, your get_item function will return the most precise type as possible.
Videos
I'll answer the 1,2 question first, then 4th then 3rd:
- "Whats the relationship between a type type "objects" and "class instances" type objects?"
- "Can I assume the ~meta API to in-built type objects is the same as that of "class instance" type objects?"
They are the same, and yes they share a common API. When the documentation describes built in types as "objects", or class instances as "objects", or a class or whatever as an "object" ... they are talking about exactly the same language construct.
- "In general, what are "objects" ..."
The object is a foundational language feature in Python that supports attributes and behaviors much like other OOPLs. All Python objects also have a class much like other classed based OOPLs. The object class is the base of the class hierarchy in Python. Thus all classes are subclasses of the object class, and all the aforementioned "objects" and instances of object - by way of inheritance.
It's worth first pointing out explicitly that in Python (2.2 and above) "type" and "class" mean the same thing (for all intents and purposes). So "int", and the rest of the so called builtin types are classes (which are represented as objects of course). For example this x = int(1) calls the int class (object) to construct an int instance object, x.
It's true to say there are two types of object in Python; "type" objects, or those that represent types, and "non-type" objects - those that don't. But it's equally true to say there are two type of integers; zero, and not zero. It doesn't mean much: Everything in Python is an object including classes. Since classes form a kind object, they are all instances of a class called "type". The type object is also an instance of type. Note you can inspect the inheritance hierarchy of class by examining the _bases_ attribute of a class object. In all cases it leads back to the object class - of course. See https://www.eecg.utoronto.ca/~jzhu/csc326/readings/metaclass-class-instance.pdf for further details on this.
- "...where is it all documented?"
Well, that's actually a good question. It should be covered in the Data Model section of the language reference, but it is sort of skimmed over. The constructor for object objects, object (that made sense) is a built in and documented with the rest of the builtins here. Also the Classes chapter of The Python Tutorial also covers this area a bit.
It's a bit hard to understand what you are asking.
A type is the class of a class. Like everything else in Python, classes themselves are objects, and you can pass them around, assign them to variables, etc. If you ask a class what its class is, you will get the answer type. If you ask a class instance what its class is, you will of course get the class.
>>> type(int)
<type 'type'>
>>> type(1)
<type 'int'>
>>> class Foo(object):
... pass
>>> type(Foo)
<type 'type'>
>>> obj = Foo()
>>> type(obj)
<class '__main__.Foo'>
(here the function type(x) is another way of doing x.__class__.)