1

Is it possible to define a function to behave as follows?

text = "def x(a):\treturn a+1"
f = ??(text)
f(1)
>> 2
4
  • 1
    @BhargavRao I think that's the question... Commented Feb 25, 2015 at 13:28
  • 1
    Just exec("print 'hello'") or any other Commented Feb 25, 2015 at 13:28
  • 2
    Why would you want to do this? If the reasoning is "because I want to define a function on the same line that I use it, and def can't be on the same line as other statements", then you can instead use lambdas: print (lambda a: a+1)(1) Commented Feb 25, 2015 at 13:32
  • @Kevin I am creating an API where the user can define functions that would be executed by other function (which are actually lambdas). Commented Feb 25, 2015 at 14:02

3 Answers 3

3

You can use exec()

text = "def x(a):\treturn a+1"
exec(text)
print x(5) # gives 6
Sign up to request clarification or add additional context in comments.

1 Comment

Now the hard part is, getting f(5) to give 6, when you don't know the contents of text and don't know that the function is currently called x, and so you can't just do f = x
1
text = "lambda a: a + 1"
f = eval(text)
f(1)    # 2

2 Comments

@bhargavrao: any method of running arbitrary code is dangerous.
@forcebru: yes, that's why I converted it to a lambda!
0

here is another solution:

text = "def x(a):\treturn a+1"
f = {}
exec text in f
f['x'](1)
>> 2

1 Comment

Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves.

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.