0
def func(param):
    #do something

Code:

    enviroment = {'func':func}
    eval('func(a)', enviroment, enviroment)

I originally want to use getattr in enviroment, but it seems not helpful

error occured when searching param a in environment, is there any way to catch the error? Then I can append the a in the environment and executing again.

any answer would be appreciated, thank you.

  • Is the question on how to catch an error? Then this might help: [Try/Except in Python](http://stackoverflow.com/questions/730764/try-except-in-python-how-do-you-properly-ignore-exceptions) – Jerrybibo Nov 24 '16 at 03:00
  • I mean when failed to search the param a in the environment, how to know the error is "cannot find the param a" – MayflowerYuan Nov 24 '16 at 03:04
  • Do you mean test whether or not an argument is provided for a function? – Jerrybibo Nov 24 '16 at 03:05

1 Answers1

1

The following code,

def func(param):
    print param

enviroment = {'func':func}
try:
    eval('func(a)', enviroment, enviroment)
except NameError as err:
    name = str(err).split("'")[1]
    enviroment[name] = "something"
print enviroment['a']

outputs:

'something'

When executing the eval statement, a NameError is returned:

NameError: name 'a' is not defined

And so we can catch that error and respond to it by extracting the 'a'.

Matt Kleinsmith
  • 1,017
  • 3
  • 13
  • 24