[Python-ideas] A user story concerning things knowing their own names

Ian Bicking ianb at colorstudy.com
Sat Mar 19 03:10:00 CET 2011


On Fri, Mar 18, 2011 at 8:58 PM, Jim Jewett <jimjjewett at gmail.com> wrote:

> On Fri, Mar 18, 2011 at 9:37 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
> > Guido van Rossum wrote:
>
> >> There's another pattern where all class attributes that have a certain
> >> property are also collected in a per-class datastructure,
>
> > I think __addtoclass__ could cover those as well,
> > if you can arrange for the relevant objects to inherit
> > from a class having an appropriate __addtoclass__
> > implementation.
>
> How do you put an attribute (such as __addtoclass__ ) on a name?  Or
> are you proposing that the actual pattern be something more like:
>
>     x=SpecialObj()
>
> And that normal initiation be handled either later, or as part of the
> SpecialObj initiation
>
>    x=SpecialObj()=5
> or
>    x=SpecialObj(); x=5
> or
>    x=SpecialObj(value=5)
>

What we're describing only applies to class variables; a top-level variable
wouldn't be affected.

Imagine for instance a column class (ORMish) that wants to know its name:

class Column(object):
    def __init__(self, **kw):
        ...
    def __addtoclass__(self, name, cls):
        self.name = name
        return self

Now if you do:

class MyTable:
    username = Column()

Then MyTable.username.name == 'username'

If you wanted to be able to reuse values, like Greg wants, you could do:

class Column(object):
    def __init__(self, kw):
        self.kw = kw
        ...
    def copy(self):
        return self.__class__(self.kw)
    def __addtoclass__(self, name, cls):
        new_obj = self.copy()
        new_obj.name = name
        return new_obj

Or you could use several different classes (e.g., BoundColumn), or... well,
there's many ways to skin a cat.

Like descriptors, only objects that implement this new method would
participate.  It's not really like a decorator, it's much more like
descriptors -- decorators like classmethod just happen to be descriptor
factories.

  Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110318/0fc3091c/attachment.html>


More information about the Python-ideas mailing list