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 foo
s?
def foo(bar):
bar += 934
return bar
foo = dehf(blah, blah, blah, blah, [...])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With