Python handles globals badly.

Steven D'Aprano steve at pearwood.info
Thu Sep 10 20:13:50 CEST 2015


On Fri, 11 Sep 2015 02:31 am, random832 at fastmail.us wrote:

> On Thu, Sep 10, 2015, at 11:59, Steven D'Aprano wrote:
>> Although, I'm not sure that I agree with the idea that "everything is an
>> expression". I think that's a category mistake, like asking for the speed
>> of dark[1], or for a bucket of cold. Some things are functional by
>> nature,
>> and other things are imperative; some may be both, but I don't think that
>> assignment is one. I think that assignment is imperative, not functional,
>> and forcing it to return a value is artificial.
> 
> Why shouldn't imperative things be expressions?

Sometimes they might be. But in general, I think it is meaningless to expect
a imperative command to have a return result. The whole point of an
imperative command is that it operates by side-effect.

For example, what would `del x` return if it were an expression instead of a
statement? I can think of two reasonable alternatives, but both feel a bit
wrong to me.

(1) Return True if x was successfully unbound, False if it wasn't. Except
that raising an exception seems more Pythonic, in which case returning True
seems redundant. It will *always* return True, unless there's an exception.
So why bother? We only bother because there's no way to *not* return a
result if "everything is an expression".

(2) Return None, like functions do by default. But again, it only returns
None, not because None is a meaningful thing to return, but because we
don't actually have a way to say "it doesn't return anything".

Or os.abort. The docs for that say:

Help on built-in function abort in module posix:

abort(...)
    abort() -> does not return!

    Abort the interpreter immediately.  This 'dumps core' or otherwise fails
    in the hardest way possible on the hosting operating system.


So, what would os.abort() return, if everything is an expression?

Obviously one can always find some arbitrary value for expressions to
return, in order to keep the invariant "all expressions return something".
But I dislike the arbitrariness of it. Some things aren't conceptually
functional expressions, they're imperative commands that (like Pascal
procedures, or Python statements) don't naturally have a return result.



> Why should all expressions return a value?

Because that's the definition of an expression in this context. An
expression is evaluated to either return a result, or raise an exception.



-- 
Steven



More information about the Python-list mailing list