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

T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top