A really bad idea.

Terry Hancock hancock at anansispaceworks.com
Fri Nov 15 16:08:23 EST 2002


On Friday 15 November 2002 10:06 am,  Tim Peters wrote:
> waiting-for-someone-to-ask-for-class-comprehensions-ly y'rs  - tim

I'm inspired.  Unfortunately, I'm still using 2.1.3 -- pardon my dust:

def meth1():
    print 1

def meth2():
    print 2

def meth3():
    print 3

# Emulate 2.2 built-in?
def dict(l):
    d = {}
    for pair in l:
        d[pair[0]] = pair[1]
    return d

class comp:
    def __init__(self):
        self.__dict__.update(dict(
            [(f.__name__,f) for f in globals().values() if callable(f) ] ))

>>> c = comp()
>>> c.meth1()
1
>>> c.meth2()
2

;-D
Still considering whether there's a more compact (or at least clearer) way to 
write that.

Practically, of course, using globals() is sort of dumb -- but imagine 
importing a module and using the module name instead.

Actually I can think of one practical use for this: In a Zope product, it's 
quite convenient to have a separate module containing ZSQL methods defined 
using Zope's SQL() factory function (that way you separate SQL and Python 
languages for the most part).  Then you could use this code with the ZSQL 
module to put ALL SQL methods from a given module into a class.  That way
you skip a whole lot of:

	mySQL_query = SQLmodule.mySQL_query

statements in the class file that have to be updated every time you change 
your SQL (which is fairly frequent).  This particular ugliness came up in the 
Zope list a few months ago, and the OP proposed writing a special parser / 
SQL extension language to do it. It turned out that this need to "shovel" the 
whole contents of an SQL module into a class was the only real problem it 
solved. This would be a simpler solution.

There's other, perhaps better, ways to do it, of course -- it might make more 
sense to just use a loop and setattr(), for example.

Just adding to the list comp madness. ;-)

Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list