I have been unable to find the answer to this on the Python documentation page (https://docs.python.org/2/tutorial/classes.html). I need to know this because I am working with large objects, and this would affect whether it is feasible to have a large object as a class variable. For example:
class LargeList:
def __init__(self, mylist):
self.mylist = mylist
if __name__ == '__main__':
x = range(0, 1000000000)
largelist = LargeList(x)
Would this object store a pointer to x?
2 Answers 2
You would have a single copy of the large list, with two references to it: the variable x in the module scope, and self.mylist in the scope of the class.
Comments
Nope, Python class variables are not pointers. But since largelist.mylist is pointing to a list, the behaviour of largelist.mylist will be like pointers.
This happens in Python with mutable types - e.g. - list, dict.
If larglist.mylist is pointing to a string, then the behaviour will be totally different since str is an immutable type i.e. it can't be mutated.
See this section of Python docs for more info
listobject created byrangewould be accessible vialargelist.mylist. They're generally referred to as "references" in Python, rather than "pointers", although the effect is much the same.class Foo ...is interpreted by executing the necessary C machinery to define a new PyObject-like type. Further, and probably more relevant here, in Python, a basiclistis really a contiguous array of pointers and it is not a pointer to a contiguous array of memory locations. When a list is constructed, it might be contiguous in memory too, but there's no guarantee it won't be fragmented, or become fragmented as items change.