[Python-ideas] A user story concerning things knowing their own names
tjreedy at udel.edu
Thu Mar 17 06:22:15 CET 2011
On 3/16/2011 4:49 PM, Terry Reedy wrote:
> On 3/16/2011 12:11 PM, Michael Foord wrote:
>> On 16 March 2011 11:10, Larry Hastings
>> <larry at hastings.org
>> As I suggested in my email on the Assignment Decorators thread this
>> morning, you could achieve this in current Python, no extension needed:
>> def assign(fn):
>> return fn(fn.__name__)
>> def content_size(name):
>> return overridable_property(name, "Size of the content area.")
>> And building on this sightly you could do the following for namedtuple:
>> >>> from collections import namedtuple
>> >>> import inspect
>> >>> def make_namedtuple(fn):
>> ... args = ' '.join(inspect.getargspec(fn).args)
>> ... return namedtuple(fn.__name__, args)
>> >>> @make_namedtuple
>> ... def Point(x, y): pass
>> >>> p = Point(1, 2)
>> >>> p
>> Point(x=1, y=2)
> If make_namedtuple were added to collections, then one could import
> *that* instead of 'namedtuple' itself.
I am not sure how serious I was when I wrote that, but after further
thought, I retract it as a serious suggestion, if indeed it was ;-).
I think both decorators are 'cute' as examples of what one can do with
decorators, and possible cookbook recipes, but not something we really
need in the stdlib. I mostly said something because they do not require
new syntax and I do not like any of the new syntax proposals.
There are many aspects of the rationale for decorators that do not apply
to the assignment case.
1. Explicit function wrapping requires the name in tripicate rather than
duplicate. Moreover, some interface wrappers for functions need fairly
long, multi-component names. I am pretty sure such need is much less for
named tuples and properties.
2. The triplicates are *not* on the same line but may be separated by an
arbitrary number of lines. This not only impedes checking that all three
are the same, but may also impede understanding of the function code.
That sometimes really requires knowing how or what the function will be
wrapped as. This is greatly aided by bringing the wrapping function back
up to (above) the def line.
For instance, @classmethod and @staticmethod explain the non-standard
signature with 'cls' or '' instead of 'self'.
For another example, twisted.internet.defer.inLineCallbacks is a
decorator that wraps a generator function as a
twisted.internet.defer.Deferred object. Knowing that a particular
generator function implements a series of data/error callbacks tor
twisted greatly helps in understanding it. The idea is 'twisted' enough
as it is ;-).
Terry Jan Reedy
More information about the Python-ideas