If One Line

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 25 22:37:00 EST 2014


alex23 wrote:

> On 26/12/2014 1:18 AM, JC wrote:
>> Is it possible in python:
>>
>> if ((x = a(b,c)) == 'TRUE'):
>> print x
> 
> One approach is to use a function in the condition to do the assignment:

Let me fix that for you:

/s/approach/bad idea/

All you have done is replace one anti-pattern (assignment as an expression)
with another (use of global variables). Your approach needs to have the
name of the variable hard-coded, if you have three such variables you have
to write three functions, you can't use local variables, and it has all the
disadvantages of global state.

And you don't even save any lines! Instead of a one-liner, you have six
lines!


>      x = None
>      def assign_to_x(val):
>          global x
>          x = val
>          return val
[...]
>      if assign_to_x(a(b,c)) == 'TRUE':
>          print(x)

Just because a programming language allows something doesn't make it a good
idea.




-- 
Steven




More information about the Python-list mailing list