0

I have a function names "myfunction". I have a string "a", I need to pass it to "myfunction" so it will give the same result as if my string was a python object name, myfunction(a) So I have

def myfunction(var):
    print var
a = 1
mystring = "a"

I need to pass "mystring" to "myfuntion" so it will behave as variable "a" was passed to it. I thought of something like this, but it won't work:

myfunction(exec(mystring))

PS. Yes, I know of the consequences of exec(), please there is no need to explain that.

2 Answers 2

4

It would be eval(), not exec:

myfunction(eval(mystring))

Alternatively:

myfunction(locals()[mystring])

Most probably you have a fundamental design problem if you think you need something like this.

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

Comments

1

No needs in exec or eval:

>>> def myfunc(var):
...     print globals()[var] * 2
...
>>> a = 12
>>> myfunc('a')
24

Comments

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.