Python language hack for C-style programmers [DO NOT USE!] :-)
Tim Chase
python.list at tim.thechases.com
Thu Mar 27 12:08:56 EDT 2014
Multiple times, I've seen someone want something like what C-style
languages offer where assignment is done in a test, something like
if (m = re.match(some_string)):
do_something(m)
So when I stumbled upon this horrific atrocity of language abuse and
scope leakage, I thought I'd share it.
if [m for m in [regex.match(some_string)] if m]:
do_something(m)
And presto, assignment in an if-statement. It even "works" in
while-statements too:
while [m for m in [regex.match(some_string)] if m]:
some_string = do_something(m)
That said, it's ugly, far more opaque/inefficient than the traditional
m = regex.match(some_string)
if m:
do_something(m)
and if I ever caught someone on my dev teams doing this in production
code, their backside would receive a stern conversation with my
footwear.
Friends don't let friends program C in Python. ;-)
-tkc
More information about the Python-list
mailing list