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

Guido van Rossum guido at python.org
Fri Mar 18 05:18:10 CET 2011

On Wed, Mar 16, 2011 at 2:28 AM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> I just experienced an obscure bug resulting from copying
> and pasting an overridable_property and forgetting to
> change the passed-in name:
>  content_size = overridable_property('size',
>    "Size of the content area.")
> which should have been
>  content_size = overridable_property('content_size',
>    "Size of the content area.")
> This was quite difficult to track down, because the result
> was to effectively make it an alias of *another* property
> I have called 'size'. They happen to be near enough to the same
> thing that the error went unnoticed for quite some time.
> If I could write my overridable_property declarations
> without having to repeat the name, this kind of thing would
> not be able to happen.

I appreciate the user story. I also appreciate what Ian said: that
this is often solved using a metaclass (in fact it is now a very
common pattern) but that everybody does it somewhat differently. And I
appreciate that Greg's use case is not solved by a metaclass (even if
we turned the pattern into a metaclass or class decorator in the
stdlib, which might be a good idea regardless).

At the same time, it seems that there aren't a lot of specific
examples besides namedtuple (which seems to cause lots of emotions and
is I think best left alone) and Greg's overridable_property. So,
unless we can come up with a really nice way (either syntactical or
perhaps through a magic builtin) to give functions like
overridable_property() access to the LHS name, and find more use
cases, I don't see this happening.

I really don't like "assignment decorators" (which aren't the same
thing at all as class or function decorators, no matter how much I
squint) nor most other solutions (e.g. ":=" -- too subtle, and might
well mean something else). But I'm not precluding that someone will
come up with a better solution. In the mean time, as long as it's just
one use case I still like spelling it using a function decorator:

def content_size(): "Size of the content are"

The overridable_property can then access the __name__ and __doc__
attributes of the function passed into it, assert that it has no
arguments using the inspect module, and return an appropriate instance
of the OverridableProperty class. Voilà, decorated assignment. :-)

PS. Greg: is your current overridable_property part of some open
source code that you've published yet? Searches for it mostly seem to
turn up recent discussions here...

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list