0

The below results in RuntimeError: dictionary changed size during iteration.

class New:
    
    def __init__(self):
        self.long_name_a = None
        self.long_name_b = None
        self.add_value()
    
    def add_value(self):
        for att in self.__dict__:
            self.att = att

new = New()
assert new.long_name_a == 'long_name_a'

Putting aside option self.long_name_a = 'long_name_a' or self.long_name_a = add_value('long_name_a'), is this possible?

aeiou
  • 337
  • 1
  • 7
  • Yes, you cannot modify a dict while you iterate over it. But it really isn't clear what you are *trying* to accomlish in `add_value`... what do you think `self.att = att` *does*? – juanpa.arrivillaga Oct 05 '22 at 18:01

1 Answers1

1

That code does not do what you expect. That creates a new member called self.att. What you meant to write was:

    def add_value(self):
        for att in self.__dict__:
            setattr( self, att, att )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30