Skip to content Skip to sidebar Skip to footer

Function Internally Using Exec(astring) With A Variable Definition Inside Astring Can Not Return The Variable In Python 3

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

Solution 1:

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)
  returneval('variable')

function('42')

returns as expected 42.

Or simply strip that assignment:

def function(astring):
  returneval(astring)

Post a Comment for "Function Internally Using Exec(astring) With A Variable Definition Inside Astring Can Not Return The Variable In Python 3"