[Python-ideas] Method chaining notation
Andrew Barnert
abarnert at yahoo.com
Sat Feb 22 00:07:15 CET 2014
From: Masklinn <masklinn at masklinn.net>
Sent: Friday, February 21, 2014 2:43 PM
> On 2014-02-21, at 23:00 , spir <denis.spir at gmail.com> wrote:
>> Also, I don't find the idea of having a builtin construct for such
> hacks a good idea. Libs for which this may be practicle can return self --end of
> the story.
>
> That has two issues though:
>
> 1. it makes chainability a decision of the library author, the library
> user gets to have no preference. This means e.g. you can't create
> a tree of elements in ElementTree in a single expression (AFAIK
> Element does not take children parameters). With cascading, the
> user can "chain" a library whose author did not choose to support
> chaining (in fact with cascading no author would ever need to
> support chaining again).
>
> 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.
I think this is almost always a bad thing to do, and a feature that encourages/enables it is a bad feature just for that reason.
If you just want to remove an element from a list or a dict, you use a del statement. There's no reason to call pop unless you want to result. Misusing pop to allow you to wedge a statement into an expression is exactly the same as any other misuse, akin to the "os.remove(path) except IOError: None" from the other thread.
Look at it this way: If someone wrote this, would you congratulate him on his cleverness, or ask him to fix it before you waste time reviewing his code?
[d.pop(key) for key in get_keys()]
More information about the Python-ideas
mailing list