[Tutor] 'or' in assignment (not if statement)?
steve at pearwood.info
Fri Dec 10 04:50:11 CET 2010
Hugo Arts wrote:
> Doesn't short-circuit evaluation refer specifically to the behavior
> where arguments are only evaluated if they need to be? It's a very
> useful feature, but not technically required for the "val = val or 1"
> behavior to work.
Some languages (Pascal comes to mind) doesn't have short-circuit
behaviour at all. If I've understood correctly, some languages (Algol, I
think, but don't quote me) have short-circuiting function parameters, so
you could do this:
x = 0
and the argument x/0 would only be evaluated if the function actually
tried to use it.
Python has short-circuit behaviour for:
x or y
x and y
true_value if condition else false_value
> Also, returning on of its operands rather than a boolean is hardly a
> quirk, since basically all dynamic languages do it ever since perl
> made "val = val or 1" an idiom (at least, I think it was perl).
Yes, it's certainly useful and not deprecated. At worst, it's less
common since the introduction of the ternary if operator, but it's still
useful. You can do things like this:
extras =  # Global list of extra names to use.
def func(x, names=None):
# Do something with x and an optional list of names.
names = names or extras or ['my', 'internal', 'list', 'of', 'names']
This means that the names actually used will be the first of:
- the function argument
- the global extras
- the built-in internal list
which is not empty. So you can override the internal list globally by
setting extras, and you can override the global list by passing a list
of names to the function.
More information about the Tutor