Hernan
Hernan

Reputation: 6063

Classes or closures for simple things in Python

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.

Upvotes: 21

Views: 1226

Answers (3)

Paddy3118
Paddy3118

Reputation: 4772

If you want performance and only want access to values, then it would be best to use a built-in data type such as a tuple for best performance

Upvotes: -1

wheaties
wheaties

Reputation: 35970

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.

Upvotes: 8

Tom Zych
Tom Zych

Reputation: 13576

I'd write the more complex functions and profile them.

Upvotes: 3

Related Questions