0

I have a python 3 function that takes a string of commands, say 'np.pi' and then tries to define a variable with that string. Then I try to return the variable, this however does not work.

input = np.pi
astring = 'funcD(funcC(funcB(funcA(input))))'

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return variable

In:  a = function(astring)
Out: NameError: global name 'variable' is not defined

Nothing seems to have happened. What I would like is to have the function return the output of the command in the string. The string contains several functions who have each other as input like below. I tried putting the exec after return without adding the variable = and then call the function with a = function(astring) but that did not work either. I believe I cant use eval because my string has functions in it.

Leo
  • 1,757
  • 3
  • 20
  • 44
  • 1
    Works for me, python 2.7.5 on Fedora 19. Do you actually *call* your function? – Andrey Sobolev Sep 09 '13 at 10:50
  • 1
    See [How does exec work with locals?](http://stackoverflow.com/q/1463306/222914) – Janne Karila Sep 09 '13 at 10:55
  • @AndreySobolev I did call it, I will add it to the question. I use python3, maybe thats the difference. – Leo Sep 09 '13 at 11:44
  • @JanneKarila Thank you for that link. I searched the site but did not find that one. Did not do a search with the term 'locals' as I did not know it before. It answers my question. I will flag my question as a duplicate. – Leo Sep 09 '13 at 11:46
  • 1
    The _output_? And assignment has no output. If you just want the assigned thing, don't use `exec` to assign it, just `return` its `eval` instead: `return eval(astring)`. – Alfe Sep 09 '13 at 12:09
  • I thought I couldnt use eval on functions. But it seems to work, thank you. – Leo Sep 09 '13 at 12:14

1 Answers1

2

You didn't state what you expected from the answer, so I take a guess: You want to make this work.

Try it using eval:

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return eval('variable')

function('42')

returns as expected 42.

Or simply strip that assignment:

def function(astring):
  return eval(astring)
Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Thank you. I added further explanation as per your request. I understood from other SO questions that I cant use eval because the commands in my string call functions. – Leo Sep 09 '13 at 12:07