I have been learning about Python functions and functions in general, and I came across this idea of anonymous functions, whose advantages, among others, are apparently the ability to keep the namespaces clean as well as not allocating extra memory because a function is only executed once it is assigned to a variable.
In Python, from what I understood, the only way to create anonymous functions is to wrap them in another function. So I came up with the idea of creating a single container for multiple anonymous functions in the code and addressing them through the selector which is essentially calling the wrapper with a parameter:
def anonwrap(selector):
if selector == "addition":
def anon(param1, param2):
return param1 + param2
return anon
elif selector == "the meaning of life":
def anon(param1):
return param1 + " 42"
return anon
else:
def anon(*args, **kwargs):
print("no idea")
return anon
select = anonwrap("addition")
print(select(10, 20))
select = anonwrap("the meaning of life")
print(select("the meaning of life is"))
select = anonwrap("hello")
print(select("blah", 9001))
My question is, once the anonwrap
function gets defined in the code, does the interpreter automatically allocate memory for all the inner functions, or does it only allocate memory for a specific inner function once it gets called from the main code?
How effective is this code at all?