[Python-ideas] Augmented assignment syntax for objects.
Steven D'Aprano
steve at pearwood.info
Thu Apr 27 18:43:32 EDT 2017
On Wed, Apr 26, 2017 at 11:29:19PM +0100, Erik wrote:
> But, if we're going to bikeshed and there is some weight behind the idea
> that this "papercut" should be addressed, then given my previous
> comparisons with importing, what about having 'import' as an operator:
>
> def __init__(self, a, b, c):
> self import a, b
> self.foo = c * 100
[snarky]
If we're going to randomly choose arbitrary keywords with no connection
to the operation being performed, can we use `del` instead of `import`
because it's three characters less typing?
[/snarky]
*wink*
But seriously, I hate this idea. `import` has certain semantics that
don't apply here:
- import goes through the full import system (sys.modules, reading
files from disk, sys.path, etc.); this "self import ..." does not;
- import creates local variables; this "self import ..." does not.
The semantics are very different and there's little or no connection
between importing a module and setting an attribute on self.
If we're going to discuss pie-in-the-sky suggestions, here is an only
semi-serious suggestion. A statement that injects identifiers into
an explicitly given name space:
inject spam, eggs as cackleberry, cheese into self
(If you don't like "inject", I'm okay with "load" or even "push".)
This would be equivalent to:
self.spam = spam
self.cackleberry = eggs
self.cheese = cheese
Presumably it would be implemented a little more efficiently, e.g. only
a single lookup for self, etc. Note that the target is completely
general: you can inject into any object which will accept setting
attributes:
inject spam, eggs into namespace
If the "inject as" form is used, the value can be any expression:
inject x + 1 as y into namespace
otherwise the value must be a valid identifier but not necessarily a
local variable.
If I were designing a language from scratch, one with a maximalist
approach to syntax, I'd take this seriously. But Python has relatively
minimal syntax and keywords, and the problem this solves isn't big or
important enough for the disruption of adding a new keyword.
--
Steve
More information about the Python-ideas
mailing list