Reputation: 15357
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.
Upvotes: 4
Views: 251
Reputation: 838146
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.
Upvotes: 8
Reputation: 5710
Writing code in one language but using the styles and limitations of another language are never a good idea in the long run. Your python code should always be pythonic.
That said, make sure your code is readable assuming that the person reading the code understands python syntax, or at least enough to google the rest.
Upvotes: 1
Reputation: 798606
It is syntactically and semantically valid, but it certainly isn't Pythonic. Consider using the Strategy pattern instead.
Upvotes: 3