4
allInstancesOfFoo = []

class foo(object):
    def __init__(self)
        allInstancesOfFoo.append(self)

bar1=foo()
bar2=foo()
bar3=foo()

Will doing this create copies of bars 1-3 and place them in that list, or will it simply add a 'reference' of sorts to them in that list. And, I know there are no C-style references in Python, but I can't think of a better word for it at the moment.

Also, sorry if this is a ridiculous question, I just want to make sure that doing this won't hog resources it doesn't need to.

  • 1
    Just run the code and print out the contents of `allInstancesOfFoo` –  Mar 01 '13 at 20:23
  • 2
    See [Drastically Improve Your Python: Understanding Python's Execution Model](http://www.jeffknupp.com/blog/2013/02/14/drastically-improve-your-python-understanding-pythons-execution-model/) –  Mar 01 '13 at 20:27
  • 2
    Just a note on style: python encourages the style of "CapWords" for classes and "name_with_underscores" for methods, functions and variables. In other words, it would be more expected to have `class Foo` and variable `all_instances_of_foo` – mgilson Mar 01 '13 at 20:34

1 Answers1

3

In this case, your list will contain references to the original objects (bar1,bar2 and bar3) -- No copies will be made.

For example:

allInstancesOfFoo = []

class foo(object):
    def __init__(self):
        allInstancesOfFoo.append(self)

bar1=foo()
bar2=foo()
bar3=foo()
print bar1 is allInstancesOfFoo[0]  #True

As a side note, if you make a shallow copy of allInstancesOfFoo, that also only makes new references to existing objects:

all_instances_of_foo = allInstancesOfFoo[:]
print all(x is y for x,y in zip(all_instances_of_foo,allInstancesOfFoo))  #True
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • So essentially no extra resources/memory will be taken by the lists? – wanabeswordsman Mar 01 '13 at 20:23
  • 1
    @wanabeswordsman: Well, there's an extra pointer (4-8 bytes), and (in CPython) the refcount is bumped up. But that's it. – abarnert Mar 01 '13 at 20:25
  • 1
    Very minimal, correct. Ultimately, the implementation needs to keep track of a little data for each reference, but that overhead is probably only a few bytes here and there (`sizeof(pointer)`). – mgilson Mar 01 '13 at 20:25
  • Thank you very much! I'll be sure to accept your answer when it lets me. :D – wanabeswordsman Mar 01 '13 at 20:26