1

This is not a duplicate of creating a function object from a string because that is a Python 2 solution with exec not as a function()

Trying to implement that solution in Python 3 gets this:

d = {}
exec("def f(x): return x")in d
print(d)

returns:

{}

So the question is, how do I create a function in Python 3 from an arbitrary string? (In my case read in from a YAML file, but that's a side issue.)

10
  • 5
    I don't understand what the in d part is trying to do. If you just exec that code, you will be able to call f(x) in your code. Either way, I would never recommend running arbitrary strings, this seems like an XY problem Commented Jul 18, 2018 at 16:04
  • I need the function object so I can place it in an object to be used later. The use must be able to create an arbitrary function that uses data from the object. Commented Jul 18, 2018 at 16:05
  • @user3483203 that's part of the syntax of the exec keyword in Python 2 (apparently). It seems like a honkin' bad idea to me. Commented Jul 18, 2018 at 16:05
  • Right. Understand that folks don't know my application. Moving beyond the question of whether others would do it, is it still possible to create a function object from an arbitrary string? Commented Jul 18, 2018 at 16:06
  • 1
    @sP_ No, it returns {} because d is an empty dictionary. The middle line of code just checks if None is a member of d, which it is not. Commented Jul 18, 2018 at 16:11

2 Answers 2

3

X in d , returns True if X is found in element d.

Your exec call is defining function f in global scope.

This appears to do what you want it to:

>>> d = {}
>>> exec("def f(x): return x", d)
>>> d["f"]("Hello World")
'Hello World'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I see now how the exec has changed (and now that I understand it, improved.)
0
>>> d={}
>>> exec("def f(x): return x",None,d)
>>> d['f'](2)
2
>>>

1 Comment

Can you please provide a brief explanation?

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.