title: Dynamically add properties to instances in Python
body: <p>I've got essentially an elaborate wrapper around a list of dictionaries:</p>
  
  <pre><code>class Wrapper(object):
      def __init__(self, data):
          self.data = data
  
      def get(self, attr):
          return [d[attr] for d in self.data]
  </code></pre>
  
  <p>So, </p>
  
  <pre><code>Wrapper([{'x': 23}, {'x': 42}, {'x': 5}]).get('x')
  </code></pre>
  
  <p>returns <code>[23, 42,  5]</code>. Now I want to assign shorthand properties, so that <code>Wrapper.x</code> will return the same as <code>Wrapper.get('x')</code>. I don't know what keys are present in the <code>data</code> a priori, so my current approach is (adapted from <a href="https://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python">this question</a>:</p>
  
  <pre><code>class Wrapper(object):
      def __init__(self, data):
          self.data = data
          for key in data[0].keys():
              setattr(self, key, property(lambda self: self.get(key)))
  </code></pre>
  
  <p>So, assumption is that all elements of data have the same keys and they're all valid identifiers in python. But then, <code>Wrapper(...).x</code> returns <code>&lt;property at 0x10a3d4838&gt;</code> What am I doing wrong?</p>