Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?)

Terry Reedy tjreedy at udel.edu
Mon Mar 24 09:33:53 CET 2008


"Steven D'Aprano" <steve at REMOVE-THIS-cybersource.com.au> wrote in message 
news:13ue0gsj76m6070 at corp.supernews.com...
| Unfortunately there's nothing we can do to fix that error. Even though
| the function object has an attribute "__name__" (also known as
| "func_name") which is set to spam, it isn't used for tracebacks. Instead,
| the label comes from a read-only attribute buried deep in the function
| object:
|
| >>> tasty_stuff.func_code.co_name = 'yummy meat-like product in a can'
| Traceback (most recent call last):
|  File "<stdin>", line 1, in <module>
| TypeError: readonly attribute

The fact that .func_name (which is writeable) is not used at first 
surprised me until I remembered that code objects can potentially be used 
by multiple function objects and hence are not connected to any one in 
particular.

| This is a mistake, in my opinion. It's an arbitrary decision to make this
| read-only (as far as I can tell), which goes against the grain of
| Python's "we're all consenting adults here" philosophy.
|
| By the way, in case you're thinking that wanting to change the (so-
| called) name of a function is a silly think to do, not at all. Consider
| factory functions:
|
| def factory(how_much):
|    def f(n=1):
|        for i in range(n):
|            print "I love spam a %s" % how_much
|    return f
|
| Every function created by the factory has the same "name", no matter what
| name you actually use to refer to it. factory('little') and
| factory('lot') both uselessly identify themselves as "f" in tracebacks.

workaround:
>>> ftext = 'def %s(): pass'
>>> exec ftext%'ftest'
>>> ftest
<function ftest at 0x00C01070>

so:
def factory(how_much):
    'param how_much MUST be a legal name'
    exec '''def %(how_much)s(n=1):
    for i in range(n):
        print "I love spam a %(how_much)s"''' % {'how_much': how_much}
    return locals()[how_much]

f2=factory('much')
print f2.func_name

prints 'much'
But certainly setting .co_name directly would be easier

Terry Jan Reedy






More information about the Python-list mailing list