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"

2

1 Answer 1

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.

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

1 Comment

Thanks for this but I was hoping there is something other than eval.

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.