c[:]()

Warren Stringer warren at muse.com
Mon Jun 4 01:43:37 CEST 2007


> Anyway, the code below defines a simple "callable" list; it just calls
> each contained item in turn. Don't bother to use [:], it won't work.
> 
> py> class CallableList(list):
> ...   def __call__(self):
> ...     for item in self:
> ...       item()
> ...
> py> def a(): print "a"
> ...
> py> def b(): return 4
> ...
> py> def c(): pass
> ...
> py> def d():
> ...   global z
> ...   z = 1
> ...
> py> z="A"
> py> x = CallableList([a,b,c,d])
> py> x()
> a
> py> z
> 1
 
I just ran this example. I think the class is simpler than Mikael's example:

    class CallableList(list):
        def __call__(self,*args,**kwargs):
            return [f(*args,**kwargs) for f in self]

    def a(): return 'a called'
    def b(): return 'b called'
    c = CallableList([a,b])()

Though Mikael's returns a list containing all the returns of each item,
which comes in handy for some use cases. So, your examples with Mikael's
CallableList, yields a list [None,4,None,None]

Mikael's shows how such a construct could simplify homogenous lists. Yours
shows how it might obfuscate heterogeneous lists. 

Your example is less of an edge condition than ["string", func], as these
are all funcs. It best shows why supporting a general case of c[:]() might
lead to more obscure code.
 
My use case is very homogenous. I am porting a C++ parsed script that
contain 1000's of calls with no return value. So, I'll probably be using a
cross between your version and Mikael's. 

There is another incentive for a callable list. Much of my script has deep
nested namespaces, like a.b.c.d(). In C++, deep nesting is cheap, but in
python, it is expensive because each dot is, in its own right, a function
call to __getattr__. Collecting all the calls into list preprocesses all of
the dots.

Thanks for the example

> I begin to think you are some kind of Eliza experiment with Python
> pseudo-knowledge injected.

BTW, my favorite Eliza implementation of all time is the one written by
Strout, Eppler, and Higgins ... in Python, of course.




More information about the Python-list mailing list