Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we define a function without using the `def` keyword?

It's possible to define a class without using the class keyword.
The following ...

get_i = lambda self: self.i    
get_i.__name__ = 'get_i'
get_i.__qualname__ = 'Klass2.get_i'
dct = dict(a=1, i=4, get_i=get_i)    
Klass2 = type('Klass2', (SuperK,), dct)

... produces the same end result as:

class Klass1(SuperK):
    a = 1
    i = 4
    def get_i(self):
        return self.i

How can we do something similar for functions? That is, how can we define a function without using the def or lambda keywords? What might a pure-python implementation of dehf look like if the following two pieces of code created identical foos?

def foo(bar):
    bar += 934
    return bar

foo = dehf(blah, blah, blah, blah, [...])
like image 205
Toothpick Anemone Avatar asked Oct 18 '25 13:10

Toothpick Anemone


1 Answers

You can create functions by calling the types.FunctionType constructor. Keep in mind however that this constructor is undocumented and implementation specific. In CPython, we can figure out the constructor arguments by calling help(types.FunctionType):

class function(object)
 |  function(code, globals[, name[, argdefs[, closure]]])
 |  
 |  Create a function object from a code object and a dictionary.
 |  The optional name string overrides the name from the code object.
 |  The optional argdefs tuple specifies the default argument values.
 |  The optional closure tuple supplies the bindings for free variables.

To create a code object, we can use compile:

code = compile('print(5)', 'foo.py', 'exec')
function = types.FunctionType(code, globals())

function()  # output: 5
like image 183
Aran-Fey Avatar answered Oct 20 '25 02:10

Aran-Fey