1

How to print pass arguments to code object via exec and print in python? Below are just few examples to see how things work in a generic case.

def foo(x, y):
    return x * y

exec(foo.func_code {'x': 1, 'y': 5}) # This didn't work

def bar():
    return 3*5

exec(bar.func_code) # this got executed but I couldn't print it?
user1870400
  • 6,028
  • 13
  • 54
  • 115

1 Answers1

-1

I don't think you'll be able to pass arguments to a code object without using "black magic". Why not use exec("print foo(1, 5)")?

In your both examples, nothing is printed because exec simply executes xxx.func_code, but function foo and bar contain no print statements.

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • I understand it contains no print statements but why cant we do something more like print (exec(code_object)) or something like that and how to pass arguments to any function using code_object and exec. That is more of my intention. – user1870400 Aug 24 '16 at 02:33
  • `exec(code_object))` return None, so ` print (exec(code_object)) ` is meaningless. See [Python: How to pass arguments to the __code__ of a function?](http://stackoverflow.com/questions/5874558/python-how-to-pass-arguments-to-the-code-of-a-function) . – Em L Aug 24 '16 at 03:24
  • @EmL But technically speaking, `exec(foo.func_code, {'x': 1, 'y': 5})` is not __passing__ arguments. – nalzok Aug 24 '16 at 03:38