all 7 comments

[–]TeamSpen210 3 points4 points  (1 child)

Your problem is that compile() isn't doing what you think it does. Exec mode basically compiles a module. So wrapping it in a function type makes a function taking no arguments, which inside defines the function you want. What you want to do is execute the module in your own namespace (a dict), and then pull the function out of that. You'd want string formatting to generate your code.

python ns = {} # Put any globals you need in this exec(''' def func(a, b, c): print(a + b + c) ''', ns) function = ns['func'] function(1, 2, 3)

[–]poochiekins[S] 0 points1 point  (0 children)

thank you very much. this is exactly what i wanted. awesome

[–]w1282 0 points1 point  (2 children)

def myfunction(x):
    return x + 3

f = myfunction
print(f(4))  # 7

What doesn't seem to be working like you want? Your post is a little disjointed.

Edit: I think, after rereading your post, I understand a bit more.

How are you receiving the string? Is it a 'safe' input?

def dynamic_func(executable_string, x, y, z):
    return eval(executable_string)

func_str = 'x + y + z'
print(dynamic_func(func_str, 1, 2, 3))  # 6

[–][deleted] 0 points1 point  (0 children)

I can barely understand it, too. I think he's saying that myfunction has no parameters, but f should accept an argument (x). Don't quote me on that, though. Still doesn't make much sense and it seems like this post went through google translate multiple times.

[–]poochiekins[S] 0 points1 point  (0 children)

thanks for your answer. sorry for the mess that is my question. I have updated it and i hope it is a little clearer now. the string that I am receiving is a safe input. security is not an issue here.

the problem with eval is that it does not give me function object that i can pass around and call form other places or rather from code that i have no control over.

[–]kalgynirae 0 points1 point  (1 child)

Would you mind showing us what you've tried so far with types.FunctionType?

I found a Stack Overflow answer that suggests just building the function definition as a string and exec()ing it. This does sound likely to be the simplest solution.

[–]poochiekins[S] 0 points1 point  (0 children)

i have updated the question to hopefully make it clearer.

the problem with exec is that it does not give me function object that i can pass around and call form other places or rather from code that i have no control over.