Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes or closures for simple things in Python

Tags:

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.

like image 562
Hernan Avatar asked Mar 25 '11 09:03

Hernan


People also ask

What are closures used for in Python?

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.

What are classes in Python good for?

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.

When should closures be used?

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.

What are closures with example?

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.


1 Answers

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.

like image 74
wheaties Avatar answered Nov 13 '22 06:11

wheaties