Search code examples
pythonstringfunctioninstancegetattr

Python - How to call an instance from a given string?


I want to call the function bar() from the instance foo, just like this:

foo.bar()

But both instance and function names come from a given string. I tried getattr but it just let me use a string for the function, not the instance:

strbar = 'bar'    
getattr(foo, strbar)()

What I want to do is something like:

strfoo = 'foo'
strbar = 'bar'
getattr(strfoo, strbar)()

But it gives me:

AttributeError: 'str' object has no attribute 'bar'

I know a dictionary could be an option, but that makes me write a really long dictionary.


Solution

  • The best way would be to have a dictionary or a similar structure. However you could use eval which is evil. Or you can get your instance from the locals() dictionary:

    getattr(locals()[instance_name], attribute_name)
    

    I would think about redesigning your code. There must be a better solution as eval or locals ... like a dictionary ...