I have something as follows:
mystring="myobject"
def foo(object):
pass
And I would like to call foo(myobject) using mystring directly, in the same way like getattr(myclass, "mymethod").
Any help would be welcome. Thanks
You can resolve the value of myobjectfrom the module where it is defined with getattr. If it is in the main module, this should work:
import __main__
mystring = 'This is a test.'
def foo(object):
print object
variableName = 'mystring'
foo(getattr(__main__, variableName))
variableName = 'variableName'
foo(getattr(__main__, variableName))
This should print
This is a test.
variableName
The import of the main module is necessary for variables from the main scope.
Edit: You can also get the content of the string with very dangerous eval(). Just replace foo(getattr(__main__, variableName)) with foo(eval(variableName)).
foo(mystring)? Yes it is, if there is some other mystring residing in a scope closer to foo().mystring. The reason for that is, that you could use a variable instead of a string literal. See my edit.mystring multiple times, you should parse it once with myvalue = eval(mystring), and use myvalue as parameter.mystring = '[ (1,1), (2,2), (3,3) ]' , I want to call foo([ (1,1), (2,2), (3,3) ]) . There is the possibility to use exec('foo('+mystring+')' ) , but if foo had many arguments or the list inside mystring was used frequently, that wouldn't be quite efficient, and the exec is quite annoying with the return .
exec()function or a way to get argument offoo()insidefoo()using something likegetattr(). I can't think of a context where you will find the 2nd one handy.