title: Defining __repr__ when subclassing set in Python
body: <p>I'm trying to subclass the <code>set</code> object in Python, using code similar to the below, but I can't work out a sensible definition of <code>__repr__</code> to use.</p>
  
  <pre><code>class Alpha(set):
      def __init__(self, name, s=()):
          super(Alpha, self).__init__(s)
          self.name = name
  </code></pre>
  
  <p>I'd like to define <code>__repr__</code> in such a way that I can get the following output:</p>
  
  <pre><code>&gt;&gt;&gt; Alpha('Salem', (1,2,3))
  Alpha('Salem', set([1, 2, 3]))
  </code></pre>
  
  <p>However, if I don't override <code>__repr__</code>, the output I get ignores the <code>name</code> value…</p>
  
  <pre><code>&gt;&gt;&gt; Alpha('Salem', (1,2,3))
  Alpha([1, 2, 3])
  </code></pre>
  
  <p>…while if I do override <code>__repr__</code>, I can't get direct access to the values in the set without creating a new set instance:</p>
  
  <pre><code>class Alpha(set):
      …
      def __repr__(self):
          return "%s(%r, %r)" % (self.__class__.__name__, self.name, set(self))
  </code></pre>
  
  <p>This works, but creating a new set instance for <code>__repr__</code> that will then be disposed of seems clunky and inefficient to me.</p>
  
  <p>Is there a better way to define <code>__repr__</code> for this sort of class?</p>
  
  <p><strong>Edit</strong>: Another solution that has occurred to me: I can store the set locally. It seems slightly neater than the other options (creating and destroying something for every call of <code>__repr__</code> or using some form of string manipulation), but still seems less than ideal to me.</p>
  
  <pre><code>class Alpha(set):
      def __init__(self, name, s=()):
          super(Alpha, self).__init__(s)
          self.name = name
          self._set = set(s)
      def __repr__(self):
          return "%s(%r, %r)" % (self.__class__.__name__, self.name, self._set)
  </code></pre>