0

Lets say I have an incoming string which is a python function and I would like to convert that to a python signature. I can do that using the importlib function.

For example lets say I have an incoming string "os.getenv" and I want to resolve to the corresponding function signature. I can do something like below.

>>> import importlib
>>> fn = "os.getenv"
>>> package_signature = importlib.import_module("os")
>>> getattr(package_signature, "getenv")

How can I parse and return functions when the functions are lambda functions. For example something like fn = "lambda x: 'a' + x"

joydeep bhattacharjee
  • 1,249
  • 4
  • 16
  • 42

1 Answers1

1

You can achieve this by using eval() just like this:

function_str = "lambda x: 'a' + x"    
fn = eval(function_str)

test_input = ['a', 'b', 'c']

print(list(map(fn, test_input)))
# Outputs: ['aa', 'ab', 'ac']

Here is the corresponding section in Python Docs: eval()

You can only do this with statements, so defining a function will not work with eval. Then you would have to use exec, e.g.:

exec("def fun(x): return 'a' + x")

fun('b')
# yields 'ab'

Anywhere be careful when using eval() or exec() within your code for example when you write a web application and are thinking of executing some user input. There are a couple of ways to exploit such functionality. Just google for something like "exec python vulnerability" or similar and you will find a lot of information.

Igl3
  • 4,900
  • 5
  • 35
  • 69