Python language hack for C-style programmers [DO NOT USE!] :-)

Tim Chase python.list at
Thu Mar 27 17:08:56 CET 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)):

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]:

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:

and if I ever caught someone on my dev teams doing this in production
code, their backside would receive a stern conversation with my

Friends don't let friends program C in Python. ;-)


More information about the Python-list mailing list