[Python-ideas] Repr of lambda
Steve Barnes
gadgetsteve at live.co.uk
Mon Dec 18 02:54:17 EST 2017
On 18/12/2017 06:11, Ivan Pozdeev via Python-ideas wrote:
> On 17.12.2017 22:20, Serhiy Storchaka wrote:
>> Currently repr of doesn't contain much of information besides that it
>> is a lambda.
>>
>> >>> lambda x: x**2
>> <function <lambda> at 0x7f3479b74488>
>>
>> All lambdas have the same repr, different only by unreadable
>> hexadecimal address.
>>
>> What if include the signature and the expression of the lambda in its
>> repr?
>>
>> >>> lambda x: x**2
>> <lambda x: x**2>
>>
> It's the same for named functions:
>
> In [1]: def ditto(a): return a
>
> In [2]: ditto
> Out[2]: <function __main__.ditto>
>
> Are you intending to do the same for them?
>> This would return an old feature of Python 0.9.1
>> (https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Ftwitter.com%2Fdabeaz%2Fstatus%2F934835068043956224&data=02%7C01%7C%7C44a37122957d43015aa308d545de3321%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C636491742990321352&sdata=iAE6MDdsZJDHfUqlHlPjnf2XV%2BiRZ%2BrP%2FL%2BIQ8kKoKo%3D&reserved=0).
>>
>>
>> Repr of function could contain just the signature.
>>
>> <function foo(bar, baz)>
>>
>> But there is a problem with default values. Their reprs can be very
>> long, especially in the following case with mutable default value:
>>
>> def foo(x, _cache={}):
>> try:
>> return _cache[x]
>> except KeyError:
>> pass
>> _cache[x] = y = expensive_calculation(x)
>> return y
>>
>> Maybe the placeholder should be always used instead of default values.
>>
>> _______________________________________________
Isn't this exactly the sort of information already available via
inspect.getardspec, inspect.getsourcelines & inspect.getsource?
In [19]: import inspect
In [20]: l = lambda x: x**2
In [21]: inspect.getargspec(l)
Out[21]: ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
In [22]: inspect.getsource(l)
Out[22]: u'l = lambda x: x**2\n'
In [23]:
...: def foo(x, _cache={}):
...: try:
...: return _cache[x]
...: except KeyError:
...: pass
...: _cache[x] = y = expensive_calculation(x)
...: return y
...:
In [24]: inspect.getargspec(foo)
Out[24]: ArgSpec(args=['x', '_cache'], varargs=None, keywords=None,
defaults=({},))
In [25]: inspect.getsource(foo)
Out[25]: u'def foo(x, _cache={}):\n try:\n return _cache[x]\n
except KeyError:\n pass\n _cache[x] = y =
expensive_calculation(x)\n return y \n'
In [26]: inspect.getsourcelines(foo)
Out[26]:
([u'def foo(x, _cache={}):\n',
u' try:\n',
u' return _cache[x]\n',
u' except KeyError:\n',
u' pass\n',
u' _cache[x] = y = expensive_calculation(x)\n',
u' return y \n'],
2)
--
Steve (Gadget) Barnes
Any opinions in this message are my personal opinions and do not reflect
those of my employer.
---
This email has been checked for viruses by AVG.
http://www.avg.com
More information about the Python-ideas
mailing list