[Python-ideas] Method chaining notation
Masklinn
masklinn at masklinn.net
Sat Feb 22 15:42:07 CET 2014
On 2014-02-22, at 11:23 , spir <denis.spir at gmail.com> wrote:
>
>> 2. where a return value can make sense (and be useful) the author
>> *must* make a choice. No way to chain `dict.pop()` since it
>> returns the popped value, even if `pop` was only used for its
>> removal-with-shut-up properties. With cascading the user can
>> have his cake and eat it: he gets the return value if he
>> wants it, and can keep "chaining" if he does not care.
>
> ... not there (if I understand you well; not quite 100% sure). In fact, I find this point rather a counter-argument, something to avoid (again, if I understand). What I mean is that executing given methods should have consistent effect
Executing the method always has the same effect on its subject. That it
may not be used for the same purpose is a different issue and common:
a[k] = v can be used to add a new (k, v) pair or to update a key to a
new value (in fact Erlang's new map construct makes the difference and
provides for an update-only version). Even more so for values returned
by mutating methods, as far as I no there is no rule that they must
be used if the method is only called for its side effects.
> also, you should use the right method for the right task: if you don't want a stack's top item _and_ have it removed, then don't use 'pop', otherwise you are misleading readers (including yourself maybe, later) (note 'pop' is just a convenience utility for this very case; we could just read and remove in 2 steps).
Not only is `dict.pop` an expression (which del is not, and thus
del can't be used in some contexts where pop would be useable, e.g. in a
lambda) but dict.pop can also handle a non-existent value at the key,
doing so with `del` requires adding a supplementary conditional.
dict.pop's convenience oft makes it the right method for the right
task, even if the case is "remove the key a from the dict if it's
there".
But if you don't like the pop example there are others. The sibling
thread "Joining dicts again" for instance: with cascading it's a
non-problem, you can just cascade `update` calls on a base dict and
you get a fully correct (as opposed to dict(a, **b) which is only
correct if all of b's keys are strings) single-expression union.
More information about the Python-ideas
mailing list