title: Python: programmatic class instance variable initialisation with locals()
body: <p>I have a class with many instance variables with default values, which optionally can be overridden in instantiantion (note: no mutable default arguments). </p>
  
  <p>Since it's quite redundant to write <code>self.x = x</code> etc. many times, I initialise the variables programmatically.</p>
  
  <p>To illustrate, consider this example (which has, for the sake of brevity, only 5 instance variables and <strong>any methods omitted</strong>):</p>
  
  <p><strong>Example:</strong></p>
  
  <pre><code># The "painful" way
  class A:
      def __init__(self, a, b=2, c=3, d=4.5, e=5):
          self.a = a
          self.b = b
          self.c = c
          self.d = d
          self.e = e
  
  # The "lazy" way
  class B:
      def __init__(self, a, b=2, c=3, d=4.5, e=5):
          self.__dict__.update({k: v for k, v in locals().items() if k!='self'})
  
  # The "better lazy" way suggested
  class C:
      def __init__(self, a, b=2, c=3, d=4.5, e=5):
              for k, v in locals().items():
                  if k != 'self':
                      setattr(self, k, v)
  
  x = A(1, c=7)
  y = B(1, c=7)
  z = C(1, c=7)
  
  print(x.__dict__)  # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
  print(y.__dict__)  # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
  print(z.__dict__)  # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
  </code></pre>
  
  <p>So to make my life easier, I use the idiom shown in class B, which yields the same result as A. </p>
  
  <p>Is this bad practice? Are there any pitfalls?</p>
  
  <p><strong>Addendum</strong>:
  Another reason to use this idiom was to save some space - I intended to use it in <a href="https://micropython.org/" rel="nofollow noreferrer" title="MicroPython">MicroPython</a>. <del>For whatever reason</del> <a href="https://forum.micropython.org/viewtopic.php?t=1933" rel="nofollow noreferrer">Because locals work differently there</a>, only the way shown in class A works in it.</p>