[melbourne-pug] mapping strings to class

Bruce Cropley cropleyb at yahoo.com.au
Mon Jan 9 12:11:18 CET 2006


Hi Patrick

You can use a dictionary of functions or methods
(bound to an object or not):

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
>>> class B:
...     def meth1(self, x):
...             print x
...
>>> b = B()
>>> b.meth1
<bound method B.meth1 of <__main__.B instance at
0x57080>>
>>> B.meth1
<unbound method B.meth1>
>>> d = {"a":b.meth1, "whatever":B.meth1}
>>> d["a"]("hello")
hello
>>> d["whatever"](b, "hello")
hello

You can also pass in a global and local scope to eval:

>>> help(eval)
Help on built-in function eval in module __builtin__:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and
locals.
    The source may be a string representing a Python
expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be
any mappping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

And similarly for exec...

>>> def blah():
...     something = {1:2, 3:4}
...     exec("print something[1]", globals(),
locals())
...
>>> blah()
2

Though you may prefer something along these lines:

>>> def blah():
...     exec("def inner(a): print a")
...     inner(4)
...
>>> blah()
4

> def checkResults(self, criteria):
>     exec(criteria)
>     return criteria()

You probably want to use different names for the
string and the function.
And perhaps you could pass in self to the criteria
function so it
can access whatever attributes it needs:

class Whatever:
    ...
    def checkResults(self, criteriaStr):
        exec(criteriaStr)      # Includes "def
criteriaFunc(whatever):..."
        return criteriaFunc(self)

BTW, it's probably bad to run the exec for every item
in a large data set.

Hope that helps,
Bruce


=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Bruce Cropley
Software Development Consultant    0400 147 429 (m)
Melbourne, Australia    brucedecoy-sig yahoo.com.au
Python/Agile processes/Version control/AI/Algs./C++
http://jroller.com/comments/cropleyb/Weblog


		
____________________________________________________ 
Do you Yahoo!? 
Yahoo! Music: Vote 'Who's Next' and see your favourite band live 
http://au.music.yahoo.com/artists/whos-next/


More information about the melbourne-pug mailing list