In Python, both and
and or
will return one of their operands. With or
, Python checks the first operand and, if it is a "truthy" value (more on truthiness later), it returns the first value without checking the second (this is called Boolean shortcut evaluation, and it can be important). If the first is "falsey", then Python returns the second operand, no matter what it is:
Python 2.7.3 (default, Jan 2 2013, 13:56:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 or 3
2
>>> 0 or 3
3
With "and", much the same thing happens: the first operand is checked first, and if it is "falsey", then Python never checks the second operand. If the first operand is "truthy", then Python returns the second operand, no matter what it is:
>>> 2 and 3
3
>>> 0 and 3
0
>>> 3 and 0
0
>>> 3 and []
[]
>>> 0 and []
0
Now let's talk about "truthiness" and "falsiness". Python uses the following rules for evaluating things in a Boolean context:
- The following values are "falsey": False, None, 0 (zero), [] (the empty list), () (the empty tuple), {} (the empty dict), an empty set, "" (the empty string)
- Everything else is "truthy"
So something like password and PASS_RE.match(password)
is taking advantage of Python's short-circuit evaluation. If password
is None, then the and
operator will just return None and never evaluate the second half. Which is good, because PASS_RE.match(None)
would have thrown an exception. Watch this:
>>> 3 or []
3
>>> [] or 3
3
>>> 0 or []
[]
>>> [] or 0
0
>>> 0 and []
0
>>> [] and 0
[]
See how the short-circuiting is working? Now watch this:
>>> value = "hello"
>>> print (value.upper())
HELLO
>>> print (value and value.upper())
HELLO
>>> value = None
>>> print (value.upper())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'upper'
>>> print (value and value.upper())
None
See how the short-circuiting feature of and
helped us avoid a traceback? That's what's going on in this function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…