Posted By

caioariede on 08/02/09


Tagged

python function execution runtime


Versions (?)

Python - Create a function in runtime


 / Published in: Python
 

URL: http://caioariede.com/

The code below creates a function in python, during runtime. Change it for their needs.

  1. import types
  2.  
  3. def create_function(name, args):
  4.  
  5. def y(): pass
  6.  
  7. y_code = types.CodeType(args, \
  8. y.func_code.co_nlocals, \
  9. y.func_code.co_stacksize, \
  10. y.func_code.co_flags, \
  11. y.func_code.co_code, \
  12. y.func_code.co_consts, \
  13. y.func_code.co_names, \
  14. y.func_code.co_varnames, \
  15. y.func_code.co_filename, \
  16. name, \
  17. y.func_code.co_firstlineno, \
  18. y.func_code.co_lnotab)
  19.  
  20. return types.FunctionType(y_code, y.func_globals, name)
  21.  
  22. myfunc = create_function('myfunc', 3)
  23.  
  24. print repr(myfunc)
  25. print myfunc.func_name
  26. print myfunc.func_code.co_argcount
  27.  
  28. myfunc(1,2,3,4)
  29. # TypeError: myfunc() takes exactly 3 arguments (4 given)

Report this snippet  

You need to login to post a comment.