This method searches for the first group of word characters (ie: [a-zA-Z0-9_]
), returning the first matched group or None
in case of failure.
def test(str):
m = re.search(r'(\w+)', str)
if m:
return m.group(1)
return None
The same function can be rewritten as:
def test2(str):
m = re.search(r'(\w+)', str)
return m and m.group(1)
This works the same, and is documented behavior; as this page clearly states:
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
However, being a boolean operator (it even says so on the manual), I expected and
to return a boolean. As a result, I was astonished when I found out (how) this worked.
What are other use cases of this, and/or what is the rationale for this rather unintuitive implementation?
Conciseness (and therefore clarity, as soon as you get used to it, since after all it does not sacrifice readability at all!-) any time you need to check something and either use that something if it's true, or another value if that something is false (that's for
and
-- reverse it foror
-- and I'm very deliberately avoiding the actual keywords-or-the-likeTrue
andFalse
, since I'm talking about every object, not justbool
!-).Vertical space on any computer screen is limited, and, given the choice, it's best spent on useful readability aids (docstrings, comments, strategically placed empty lines to separate blocks, ...) than in turning, say, a line such as:
into six such as:
or more cramped versions thereof.
Far from being "unintuitive", beginners regularly were tripped up by the fact that some languages (like standard Pascal) did not specify the order of evaluation and the short-circuiting nature of
and
andor
; one of the differences between Turbo Pascal and the language standard, which back in the day made Turbo the most popular Pascal dialect of all times, was exactly that Turbo implementedand
andor
much like Python did later (and the C language did earlier...).