I would like to know more about the functions "with memory" implemented as classes vs closures.
Consider the (very) simple example:
def constant(value):
def _inner():
return value
return _inner
x = constant(5)
print(x())
vs.
class Constant():
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = Constant(5)
print(y())
Is the performance and memory consumption of any of these better? Using slots will make the class perform better?
Thanks,
Hernan
Ps.- I know that in this extremely simple example, probably it does not matter. But I am interested in more complex functions that will be called a big number of times or that will be instantiated many times.
Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem. When there are few methods (one method in most cases) to be implemented in a class, closures can provide an alternate and more elegant solution.
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In Python 2.6 I get the following:
def foo(x):
def bar():
return x
return bar
b = foo(4)
b.__sizeof__()
>>> 44
But using a class:
class foo(object):
def __init__(self,x):
self.x = x
def __call__(self):
return self.x
c = foo(4)
c.__sizeof__()
>>> 16
Which looks like the function version is a larger memory footprint.
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