Hah hah. This get's close to desirable behaviour in pure python.

class Test:
    def __init__(self,seq):
        self.seq = seq
    def __repr__(self):
        return "Test(%s)" % self.seq
    def apply_map(self,function):
        newseq = map(function,self.seq)
        return Test(newseq)
    def __getattr__(self,method):
        class Helper:
            def __init__(self,original,method):
                self.original = original
                self.method = method
            def __call__(self):
                return self.original.apply_map(lambda x: 
getattr(x,self.method)())
        #def f(method,original):
        #    return original.apply_map(lambda x: getattr(x,method))         
                              
        f = Helper(self,method)
        return f

def echo(echo):
    return echo

t = Test(['a','b','c','d'])

Below are the results:
------------------------------------------------------------------------------------------------------------------
>>> t
Test(['a','b','c','d'])
>>> t.apply_map(echo)
Test(['a', 'b', 'c', 'd'])
>>> t.apply_map(lambda x: x.upper())
Test(['A', 'B', 'C', 'D'])
>>> t.upper()
Test(['A', 'B', 'C', 'D'])
>>> t.lower()
Test(['a', 'b', 'c', 'd'])
>>> t.isalpha()
Test([True,True,True,True])

There are some limitations. Firstly, if __repr__ isn't defined (or other 
special methods are called), then it'll throw a pretty obtuse error 
message. 
I'd suggest adding some checking into the __getattr__ method, to ensure that 
the called attribute 'method' doesn't start with "_". Or, alternatively, 
check to see that the elements have the called element.

Secondly, the current implementation only works if the called method is 
called with zero parameters (other than the automagical self, of course). 
Maybe this is something we want, with a little bit of try/except in the 
Helper classes __call__ method - get it to raise an AttributeError maybe.

The thing that was giving me problems, was not realising the need for the 
set of () at the end of this line:
                return self.original.apply_map(lambda x: 
getattr(x,self.method)())

Any suggestions for improvements?

Joal Heagney

-- 
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to