string to object?

Peter Otten __peter__ at web.de
Sat Jun 12 03:05:51 EDT 2004


Guy Robinson wrote:

> To clarify things more (as I should have done yesterday):
> 
> incompatible signatures are not what I want and I do understand I need
> to instance the class first so yes
> 
> class foo:
>         def method1(self, *args):
>                 return 'one'
>         def method2(self, *args):
>                 return 'two'
> ifoo=foo()
> 
> is more like it. I have a number of classes with methods. For various
> reasons the class.method to run is only available as a string. The
> arguments arrive independently. So the question is how can I convert a
> string to a class.method object for instancing?
> 
> Pseudo python:
> 
> s = 'foo.method1'
> arg = []
> sclass,smethod = string2class(s)
> isclass = sclass.smethod(arg)
 
You are still concentrating too much on the technical details. For the
problem at hand, a plain english description would probably allow us to
come up with a better approach. Anyway, here's another variant:

class foo:
    def method1(self, *args):
        return "foo-method1%r" % (args,)
    def method2(self, *args):
        return "foo-method2%r" % (args,)

class bar:
    def alpha(self, *args):
        return "bar-alpha%r" % (args,)


def ensureInstance(klass, instCache={}):
    try:
        return instCache[klass]
    except KeyError:
        inst = instCache[klass] = globals()[klass]()
        return inst

calls = ["foo.method1", "foo.method2", "bar.alpha", "foo.method2"]
args = (1,2,3)

for call in calls:
    className, methodName = call.split(".")
    inst = ensureInstance(className)
    boundMethod = getattr(inst, methodName)
    print boundMethod(*args)

If you need the classes as namespaces rather than to preserve state you
could make the methods static methods. The code would then become

class foo:
    def method1(*args):
        return "foo-method1%r" % (args,)
    method1 = staticmethod(method1)

    def method2(*args):
        return "foo-method2%r" % (args,)
    method2 = staticmethod(method2)

class bar:
    def alpha(*args):
        return "bar-alpha%r" % (args,)
    alpha = staticmethod(alpha)


calls = ["foo.method1", "foo.method2", "bar.alpha", "foo.method2"]
args = (1,2,3)

for call in calls:
    className, methodName = call.split(".")
    staticMethod = getattr(globals()[className], methodName)
    print staticMethod(*args)

Peter
     




More information about the Python-list mailing list