class declaration shortcut

Steven Bethard steven.bethard at gmail.com
Thu Mar 1 15:58:01 EST 2007


Luis M. González wrote:
> This is the closest we got so far to the intended result.
> If there was a way to enter attributes without quotes, it would be
> almost identical.

Ok, below is the Python code so that the following works::

     class Person(Struct): "name birthday children"

Note that
* The "Person" name is not repeated
* The attribute names are not individually quoted
* It's two characters shorter than the Ruby code::

     Person = Struct.new(:name, :birthday, :children)

Is that good enough? ;-)

STeVe

class InitFromSlots(type):
     def __new__(meta, name, bases, bodydict):
         slots = bodydict.get('__doc__', '').split()
         bodydict.setdefault('__slots__', slots)
         if slots and '__init__' not in bodydict:
             parts = ['def __init__(self, %s):' % ', '.join(slots)]
             for slot in slots:
                 parts.append('    self.%s = %s' % (slot, slot))
             exec '\n'.join(parts) in bodydict
         super_new =  super(InitFromSlots, meta).__new__
         return super_new(meta, name, bases, bodydict)

class Struct(object):
     __metaclass__ = InitFromSlots
     __slots__ = ()
     def _items(self):
         for name in self.__slots__:
             yield name, getattr(self, name)
     def __repr__(self):
         args = ', '.join('%s=%r' % tup for tup in self._items())
         return '%s(%s)' % (type(self).__name__, args)
     def __iter__(self):
         for name in self.__slots__:
             yield getattr(self, name)
     def __getstate__(self):
         return dict(self._items())
     def __setstate__(self, statedict):
         self.__init__(**statedict)



More information about the Python-list mailing list