1

I'm practicing the alternative way of defining functions in Python, using FunctionType. I can create this way a simple function that prints hello world:

from types import FunctionType

foo = FunctionType(compile("print('hello world')", '', 'exec'), globals())

foo()

This function does not take positional arguments:

from types import FunctionType

foo = FunctionType(compile("print('hello world')", '', 'exec'), globals())

foo('bar')
Traceback (most recent call last):
  File "C:/Users/M/AppData/Local/Programs/Python/Python37/test_FunctionType.py", line 5, in <module>
    foo('bar')
TypeError: <module>() takes 0 positional arguments but 1 was given

How to use FunctionType to define a function that takes positional arguments?

DarklingArcher
  • 227
  • 1
  • 7
  • Here's one way to do it: from types import FunctionType foo = FunctionType(compile("def foo(name): print('hello '+name)", '', 'exec'), globals())() foo("name") Basically, you create a function that returns a function with arguments and use it. Note the function call at the end of the `foo = FunctionType...` line – pragman Dec 31 '19 at 18:15

0 Answers0