Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why deepcopy doesnt create new references to lambda function?

Tags:

python

Found this strange in python:

class SomeClass():
    def __init__(self):
        pass

a = [SomeClass()]
b = copy.deepcopy(a)

Output:

>>> a
[<__main__.Some instance at 0x10051b1b8>]
>>> b
[<__main__.Some instance at 0x10051b092>]

This is just as expected- deepcopy created new SomeClass() object for b.

But if,

f = lambda x:x+1
a = [f]
b = copy.deepcopy(a)

I get:

>>> a
[<function <lambda> at 0x10056e410>]
>>> b
[<function <lambda> at 0x10056e410>]

Why deepcopy doesnt create a new lambda instance in the second case? does that mean lambda functions are atomic?

like image 588
jerrymouse Avatar asked May 29 '12 15:05

jerrymouse


People also ask

What are the restrictions regarding lambda functions?

Technical LimitationsThe maximum time a function can run is 15 minutes, and the default timeout is 3 seconds. Obviously, this makes Lambda unsuitable for long-running workloads. The payload for each invocation of a Lambda function is limited to 6MB, and memory is limited to just under 3GB.

Can Lambda take only one input?

The function allows multiple input arguments. expression : What the function will do in a single expression. Lambda only accepts one expression, but it can generate multiple outputs.

Can Lambda return multiple values?

That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).

Do lambda functions make code more readable?

Lambda functions are a brilliant way to make code more readable and concise.


1 Answers

This applies not just to lambdas, but to functions without state more generally.

>>> def some_function(word): print word
>>> a = [some_function]
>>> a
[<function some_function at 0x1007026e0>]
>>> copy.deepcopy(a)
[<function some_function at 0x1007026e0>]

Because the functions do not store state, deepcopy does not create a new reference for them. An interesting discussion of topics similar to this issue (though not exactly the same issue) is recorded here: http://bugs.python.org/issue1515

like image 195
Karmel Avatar answered Sep 21 '22 15:09

Karmel