If you replace the __code__
object of a lambda, you basically redefine the function. The new argcount is determined by __code__.co_argcount
, so it doesnt't matter which or how many arguments the lambda took before.
If you want to pass a parameter to your compiled code, you could try to eval
your code object directly, passing your parameter in the locals
dictionaray:
code_str = """
print "this is my global x = " + x
print "And another line is done"
print param
"""
compiled = compile(code_str, "<string>", "exec")
func_template = lambda p=None: eval(compiled, globals(), {'param': p})
x = "1"
func_template()
func_template("2")
This way you can obviously only pass keyword arguments, it's not possible to use positional arguments. You could also use
func_template = lambda **kwargs: eval(compiled, globals(), **kwargs)
to pass the keyword arguments given to your function directly.
If you need a return value from your function, then you'd need to compile the code in 'eval'
mode instead, which means you have to limit your code to an expressions and can't have statements.