[Python-ideas] anonymous object support

Carl Matthew Johnson cmjohnson.mailinglist at gmail.com
Sun Aug 7 01:41:27 CEST 2011


On Aug 6, 2011, at 12:53 PM, Devin Jeanpierre wrote:

> My favorite declarative-namedtuple hack is http://code.activestate.com/recipes/500261-named-tuples/#c16
> 
> Devin

For non-link followers:

def _namedtuple(func):
    return namedtuple(func.__name__, func.__code__.co_varnames)

@_namedtuple
def Point(x,y):
    pass

That is very clever, but it kind of illustrates my point about needing a new keyword. When you see "def" don't you naturally think, "OK, what comes out of this will be a function named Point." But what comes out of this is not a function. It's a namedtuple, which is quite different…

A similar case can be made about 

@sort_list_with_keyfunc(my_list)
def result(item):
	...
	return normalized_item

It's a neat way of getting out of writing the keyfunc before the sort, but it's a bad practice because you're def-ing a sorted list, not a function.

Also a Ruby-like each can be done through abuse of decorators

@each(my_list)
def squared_list(item):
	return item ** 2

Neat but it breaks the reader's expectations. (Also, a list comprehension is shorter.)


More information about the Python-ideas mailing list