python - if (foo or bar or baz) is None: -
i've been refactoring rather crufty code , came across following rather odd construct:
#!/usr/bin/env python2.7 # ... if (opts.foo or opts.bar or opts.baz) none: # (actual option names changed protect guilty) sys.stderr.write("some error messages these required arguments")
... , wondering if ever make conceivable sense.
i changed like:
#!/usr/bin/env python2.7 if none in (opts.foo, opts.bar, opts.baz): # ...
i did fire interpreter , try first construct ... seems work if values false and last of these false values none. (in other words cpython's implementation seems return first true or last false value chain of or expressions).
i still suspect proper code should use either any() or all() built-ins added 2.5 (the code in question requires 2.7). i'm not yet sure preferred/intended semantics i'm starting on project.
so there case original code make sense?
the short-circuiting behavior causes foo or bar or baz
return first of 3 values boolean-true, or last value if boolean-false. means "if false , last 1 none".
your changed version different. if none in (opts.foo, opts.bar, opts.baz)
will, instance, enter if
block if opts.foo
none , other 2 1, whereas original version not (because none or 1 or 1
evaluate 1, not none). version enter if
when any of 3 none, regardless of other 2 are, whereas original version enter if
if last none and other 2 boolean-false values.
which of 2 versions want depends on how rest of code structured , values options might take (in particular, whether might have boolean-false values other none, such false
or 0
or empty string). intuitively version seem more reasonable, if code has peculiar tricks in it, never know corner cases might emerge.
Comments
Post a Comment