[Python-ideas] list…pushed, or something

Joao S. O. Bueno jsbueno at python.org.br
Fri Mar 29 12:40:16 CET 2013

On 27 March 2013 23:29, Shane Green <shane at umbrellacode.com> wrote:
> I'm not sure if there's anything inherently wrong with this idea, and I am
> well aware how incredibly easy it is to implement as an extension of the
> built-ins, but, I find it very useful to have variations of
> list().append(obj) and set().add(obj) that return, obj.  I've never come up
> with perfect method names; sometimes I go with past-tense versions, "added"
> and "appended" (or "pushed").  I often use these methods in places where
> performance is  a factor, such as using a set() to filter repeats from an
> input sequence.
> I was thinking it may be worth considering adding it to core, or perhaps
> creating collections types with these features, so they are high performance
> and standardized.  They can be particularly useful in generator recipes,
> etc.

I understand that the equivalent methods in other languages - sometimes
frameworks int hose languages  - allow one to chain method calls on the
parent object, so they can happly write things along:


Python style, as well placed on the thread is that methods that perform
changes to the underlying object return None, thus not allowing
such constructs to mutable objects - even though one can happily
do something like:

image_name = url.split("/")[-1].split(".")[0]

You can easily have the former behavior if you wrap your object
in a construct that, whenever a called method would return "None",
returns the original object itself. That could be placed in a utility
module - and probably there is even some "MyHacks" package on
pypi with functionality like that.

If a naive implementation fits your needs, this one would work:

class Chain:
    def __init__(self, obj, root=None):
        self.__obj = obj
    def __getattr__(self, attr):
        val = getattr(self.__obj, attr)
        if callable(val):
            self.__callable = val
            return self
        return val
    def __call__(self, *args, **kw):
        val = self.__callable(*args, **kw)
        if val is None:
            return self
        return val

>>> a = []
>>> Chain(a).append(5).append(6).append(-1).sort().append(3)
<__main__.Chain object at 0x12b6f50>
>>> a
[-1, 5, 6, 3]

I'd be -0 for something like that on the stlib, though - but if it was there,
I'd look around "functools" (but it is obviously more like an "objecttool")


More information about the Python-ideas mailing list