2

Below a runnable codesnippet with behavior I cannot explain: name_generator should create a new LetterMan object in each iteration, appends an arbitrary letter and yield it.

What happens is that on each iteration, a letter is somehow appended to the supposedly new object. The result of the script is:

class LetterMan(object):

    def __init__(self, name, letterlist=[]):
        self.letterlist = letterlist
        self.name = name

    def add_letter(self, letter):
        self.letterlist.append(letter)


def name_generator():
    for name in ["Andrew", "Bryan", "Casey"]:
        l = LetterMan(name)
        l.add_letter(name[-1])
        yield l


if __name__ == '__main__':
    n = name_generator()
    for lman in n:
        print lman.name, lman.letterlist



# Andrew ['w'] 
# Bryan ['w', 'n'] 
# Casey ['w', 'n', 'y']

I am expecting:

# Andrew ['w']
# Bryan ['n']
# Casey ['y']

Is it some sort of optimization? Why is there no new object created on each iteration? How would I achieve the expected result?

I already tried deleting the object after each yield with no result

I am using python 2.7.3 on ubuntu

ProfHase85
  • 11,763
  • 7
  • 48
  • 66
  • You can avoid this behavior by having `letterlist` default to `None` and then assign to it an empty list in the function body if it is `None`. That way, the empty list is created *when* the function is executed, not before. – Blender Apr 28 '15 at 13:08
  • Thanks @Blender (Both for the solution and for the reference) – ProfHase85 Apr 28 '15 at 13:12

0 Answers0