Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

And/Or operator between two objects in Python

I have to maintain a python package which was no longer updated since 2008. I guess the Python version the developer used back then was 2.3 or 2.4, I guess. Mostly the source code is the same, but I found something like:

fsa = (fsa and union(fsa, fsa2)) or fsa2

where fsa, fsa2, union(fsa, fsa2) are all objects. I have no idea how they work to return the new object. Could somebody please give me some hint? Also, Are these operators still allowed in Python 2.7? If no, how do I change it to make it work properly in Python 2.7?

Thanks,

like image 740
Loi.Luu Avatar asked Dec 25 '22 12:12

Loi.Luu


1 Answers

Have a look at this page in the documentation: http://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

In older versions of Python the "and-or" idiom was used to emulate a ternary operator. In modern Python you'd write the above expression as

fsa = union(fsa, fsa2) if fsa else fsa2

The trick is the short-cutting behaviour of and and or in Python:

  • a and b evaluates to b if a as a boolean evaluates to True, otherwise it evaluates to a
  • a or b evaluates to b if a as a boolean evaluates to False, otherwise it evaluates to a

Put this together and you have a nice ternary operator emulation :)

EDIT: However, as Alfe rightfully commented, this is not exactly equivalent. If union(fsa, fsa2) is False as a boolean (i.e. if the union function returned None) the existing code would return fsa2 while the "modern" code would return None or whatever false value union returned. I'd stick with the existing code since it continues to work in newer python versions and document it. Have a look at the implementation of union to decide whether you want to transition to the modern, IMHO cleaner, syntax.

like image 89
filmor Avatar answered Jan 05 '23 05:01

filmor