lambda in Python: is it returning multiple values?

To begin with let’s just have look at the old school of lambda in Python.

As we know, lambda x: return x**2 is exactly equivalent to

def squared(x): return x**2

Now look at this

>>> f1 = lambda x,y,z: x+1, y+1, z+1
>>> print(f1(1,1,1))

What will you get on the screen? A tuple of (2, 2, 2)? No. You get an error instead.

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in 
    print(f1(1,1,1))
TypeError: 'tuple' object is not callable

Now that the “returning part” of lambda is covering the contents before comma only, let’s explicitly add the brackets:

>>> f1 = lambda x,y,z: (x+1, y+1, z+1)
>>> print(f1(1,1,1))
(2, 2, 2)

Things begin to become clearer now, but what is the ‘tuple’ in the wrong example? It’s f1. Have a look at this:

>>> y = 10
>>> z = 20
>>> f1 = lambda x,y,z: x+1, y+1, z+1
>>> type(f1)<class 'tuple'>>>> print(f1)(<function <lambda> at 0x7feb222116a8>, 11, 21)

This time the lambda becomes something like def _func(x, y, z): return x+1 – only returns one value and now takes useless y and z as its arguments. You can confirm by:

>>> print(f1[0](2,-10,-20))
3

All done!

Quick note on Python syntax magics

As noted in Python 3 documention, behaviors of +, -, *, etc. can be redefined.

Specially, I would like to take notes on some special yet common methods.

__repr__ method

This method is called when you apply print on the instance. Could be useful when debugging class related problems.

__enter__, __exit__ methods

Those two methods are key components of a context manager. Refer to https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/ to get a sense on how to manage the fragile resouces with context manager.


Windows上通过pip安装Python软件包遭遇“UnicodeDecodeError”的解决

简而言之,如果你通过Windows自带的命令提示符(cmd)启动了pip,并且看到了类似下面的错误提示
in console_to_strreturn s.decode(sys.__stdout__.encoding)UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 33: invalid start byte
多半是因为命令提示符当前使用的代码页不是UTF-8。使用命令chcp,将当前代码页切换成UTF-8即可解决:

chcp 65001

NOTE:这个操作只对当前的cmd窗口有效。下次打开新的cmd窗口,仍会使用HKEY_CURRENT_USER\Console\CodePage这个键值所指定的代码页。此操作对当前用户今后打开的cmd窗口均有效,如果不想搞杂原有的代码页,建议先不带参数地键入chcp,获知原来的代码页是什么,方便改回来。