Doctest failing

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 12 00:29:05 EDT 2011


On Mon, 12 Sep 2011 01:06 pm Chris Angelico wrote:

> On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney <ben+python at benfinney.id.au>
> wrote:
>> Those are only practically the same if you ignore the practical worth of
>> a function knowing the name it was defined with. The latter does not
>> have that, hence I don't see it as practically the same as the former.
>>
> 
> I know, but in the context of explaining what "lambda" means, it's
> practically the same. Lambdas can't (afaik) have docstrings either,
> etc, etc, but in terms of defining lambda, the two are more-or-less
> equivalent.


>>> f = lambda x: x+1
>>> f.__name__ 
'<lambda>'
>>> f.__doc__ = "Return x+1"
>>> f.__name__ = "add_one"
>>> help(f)

Help on function add_one in module __main__:

add_one(x)
    Return x+1



Lambdas are functions, no more, no less. The only difference is that the
*syntax* of the lambda statement only allows a single expression rather
that the full block of a def, and no name. But because it returns an
ordinary function object, you can post-process it just like any other
function.

Unfortunately, tracebacks ignore the function.__name__ and print the code
object name:

>>> f
<function add_one at 0xb7eb425c>
>>> f("x")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: cannot concatenate 'str' and 'int' objects


and the code object name is read-only:

>>> f.func_code.co_name
'<lambda>'
>>> f.func_code.co_name = "add_one"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: readonly attribute


-- 
Steven




More information about the Python-list mailing list