2

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

1
  • Can you detail more about what you need? Maybe the syntax you think should exist. I'm not clear whether you are looking for exec() function or a way to get argument of foo() inside foo() using something like getattr(). I can't think of a context where you will find the 2nd one handy. Commented Nov 13, 2017 at 7:03

1 Answer 1

1

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)).

Sign up to request clarification or add additional context in comments.

5 Comments

How is this different from foo(mystring)? Yes it is, if there is some other mystring residing in a scope closer to foo().
My code looks up for variable named mystring. The reason for that is, that you could use a variable instead of a string literal. See my edit.
I've updated my post. If you use the content of mystring multiple times, you should parse it once with myvalue = eval(mystring), and use myvalue as parameter.
@macmoonshine Thank you for the answer, except that I don't want ` object ` to be a string. To clarify: Let's say I have 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 .
Did you see my edit and my comment? What do you mean with your last sentence?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.