Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'if' within assignment acceptable?

Tags:

python

Friday I had a discussion with someone about the following contruction:

class C(....

c = C()
d = C()
...

(c if some_boolean else d).some_function_of_class_C()

Is this kind of if statement acceptable/encouraged?

The problem is that a lot of people I work with have C experience but not that much Python experience and are not used to such statement (same like list comprehension). However, Python is not C and I think the advantages of the Python language should be used. Or not?

(btw, I use normal function names and variable names but it is just for the sake of this example to keep it sample. Also I do not only call f() but some more functions (like f().g() which I woud have to repeat completely in that case.

like image 455
Michel Keijzers Avatar asked Dec 16 '22 20:12

Michel Keijzers


1 Answers

There's nothing technically wrong with your code, but it is a little odd and surprising to see code like that.

Splitting your statement into two separate statements improves the readability:

c = c1 if some_boolean else c2
c.some_function_of_class_C()

The terrible variable names you have chosen still make it look awful. But changing the variable names also helps to improve the readability:

vehicle = plane if distance > 1000 else car
vehicle.travel()

That is a lot more readable than what you originally proposed, in my opinion, and it only took a very small change.

like image 176
Mark Byers Avatar answered Dec 22 '22 01:12

Mark Byers