[Python-Dev] Shortcut Notation for Chaining Method Calls

Michael O\'Keefe mokeefe at okeefecreations.com
Sat Feb 3 20:01:47 CET 2007


Michael O'Keefe <mokeefe <at> okeefecreations.com> writes:

I kept playing with this since my last post went live and here is a 
little more thought on these ideas. After sitting with the "Zen of
Python" document (>>> import this), I'm maybe waffling on my
previous post already so I came up with a few more options
here.

Also, to play the devil's advocate, in terms of pure space, these
ideas don't necessarily decrease the total amount of typing (see
the length stackup at the end of the post) though they would allow
a trade for horizontal typing versus vertical (down the page) typing
making for compact looking code.

I suppose what would be nice is an operator which would execute
the method indicated at left but then return back the reference
to the now modified object. This is given in the desired() function
below. Since this object doesn't exist, it can't be demonstrated.
The filtered01 and filtered02 functions demonstrate trying to
put eval to work -- not crazy about that since it has the added
baggage of the globals(), locals() plus the need to write the calls
in string format.

Anyhow, just curious for ideas and sparking discussion.

def desired():
    pass
    # IF we had a --> operator which would execute the method at 
    #     left but return a ref to object
    #return [8,9,7,1].sort()-->reverse()-->pop(0)--> # returns [8,7,1]
    # return [8,9,7,1].sort()-->reverse()-->pop(0) # returns 9
    # return [8,9,7,1].sort()-->reverse()-->pop(0) # equivalent to above

def filtered01():
    popidx=0
    return filter([8,9,7,1],'sort()','reverse()','pop(popidx)',locals=locals())

def filtered02():
    return filter([8,9,7,1],'sort()','reverse()').pop(0)

def filter(obj,*args,**kwargs):
    if 'globals' in kwargs:
        globals_=kwargs['globals']
    else:
        globals_=globals()
    if 'locals' in kwargs:
        locals_ =kwargs['locals']
    else:
        locals_ =locals()
    locals_.update(locals())
    for methodCall in args:
        eval('obj.%s'%methodCall,globals_,locals_)
    return obj

print filtered01()      # returns [8, 7, 1]
print filtered02()      # returns 9

# LENGTH STACKUP (if all statements put on the same horizontal line)
# someFunc():
# a=[8,9,7,1]a.sort()a.reverse()a.pop(0)return a
# filtered01: 
# return filter([8,9,7,1],'sort()','reverse()','pop(0)',locals=locals())
# explicitReturn():
# a=[8,9,7,1].sort().reverse()a.pop(0)return a
# newFunc01:
# return [8,9,7,1]._('sort')._('reverse')._('pop',0)
# newFunc02:
# return [8,9,7,1].self_('sort').self_('reverse').self_('pop',0)
# desired:
# return [8,9,7,1]-->sort()-->reverse()-->pop(0)-->



More information about the Python-Dev mailing list