[Python-Dev] Definining properties - a use case for class decorators?

Josiah Carlson jcarlson at uci.edu
Mon Oct 24 04:29:11 CEST 2005


Nick Coghlan <ncoghlan at gmail.com> wrote:
> 
> Reinhold Birkenfeld wrote:
> > Michele Simionato wrote:
> >> As other explained, the syntax would not work for functions (and it is
> >> not intended to).
> >> A possible use case I had in mind is to define inlined modules to be
> >> used as bunches
> >> of attributes. For instance, I could define a module as
> >>
> >> module m():
> >>     a = 1
> >>     b = 2
> >>
> >> where 'module' would be the following function:
> >>
> >> def module(name, args, dic):
> >>     mod = types.ModuleType(name, dic.get('__doc__'))
> >>     for k in dic: setattr(mod, k, dic[k])
> >>     return mod
> > 
> > Wow. This looks like an almighty tool. We can have modules, interfaces,
> > classes and properties all the like with this.
> > 
> > Guess a PEP would be nice.
> 
> Very nice indeed. I'd be more supportive if it was defined as a new statement 
> such as "create" with the syntax:
> 
>    create TYPE NAME(ARGS):
>      BLOCK
> 
> The result would be roughly equivalent to:
> 
>    kwds = {}
>    exec BLOCK in kwds
>    NAME = TYPE(NAME, ARGS, kwds)

And is equivalent to the class/metaclass abuse...

    #suport code
    def BlockMetaclassFactory(constructor):
        class BlockMetaclass(type):
            def __new__(cls, name, bases, dct):
                return constructor(name, bases, dct)
        return BlockMetaClass

    #non-syntax syntax
    class NAME(ARGS):
        __metaclass__ = BlockMetaclassFactory(TYPE)
        BLOCK

Or even...

    def BlockClassFactory(constructor):
        class BlockClass:
            __metaclass__ = BlockMetaclassFactory(constructor)
        return BlockClass

    class NAME(BlockClassFactory(TYPE), ARGS):
        BLOCK

To be used with properties, one could use a wrapper and class definition...

    def _Property(names, bases, dct):
        return property(**dct)

    Property = BlockClassFactory(_Property)

    class foo(object):
        class x(Property):
            ...

With minor work, it would be easy to define a subclassable Property
which could handle some basic styles: write once, default value, etc.

I am unconvinced that a block syntax is necessary or desireable for this
case.  With the proper support classes, you can get modules, classes,
metaclasses, properties, the previous 'given:' syntax, etc.


 - Josiah



More information about the Python-Dev mailing list