a new object definition

Steven Bethard steven.bethard at gmail.com
Fri Sep 1 17:58:23 CEST 2006


Sylvain Ferriol wrote:
> hello everybody,
> 
> i want to talk with you about a question i have in mind and i do not
> find a answer. it 's simple:
> why do we not have a beatiful syntax for object definition as we have
> for class definition ?
> 
> we can define a class in python in 2 ways:
>  1. by using the metaclass constructor
>    my_class = MyMetaClass(....)
>  2. by using the classic definition syntax:
>    class my_class(object):
>       __metaclass__ = MyMetaClass
> 
> if i want to instanciate an object, i only have one way to define it:
>  my_obj = my_class(....)
> 
> why not a better syntax like class syntax ?
> 
> example:
>>> instance my_obj:
>>>   __class__ = my_class

Michele Simionato already pointed you to `PEP 359`_.  One of the reasons 
that I withdrew it was that people seemed to feel that you could get 
most of what you want now by defining appropriate metaclasses.  In your 
case, for example, the appropriate metaclass and its usage might look like::

     >>> def instance(name, bases, dict):
     ...     cls = dict.pop('__class__')
     ...     dict.pop('__metaclass__')
     ...     dict.pop('__module__') # silently added by class statement
     ...     return cls(**dict)
     ...
     >>> class C(object):
     ...     def __init__(self, a, b):
     ...         self.a = a
     ...         self.b = b
     ...
     >>> class c:
     ...     __metaclass__ = instance
     ...     __class__ = C
     ...     a = 'foo'
     ...     b = 'bar'
     ...
     >>> c.a, c.b
     ('foo', 'bar')

Sure, it's misleading to use a class statement when you're not actually 
creating a class, but I guess people felt that wanting to do this was 
uncommon enough that they weren't worried about it.

.. _PEP 359: http://www.python.org/dev/peps/pep-0359/

STeVe



More information about the Python-list mailing list