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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With