Jump to content

Talk:Python Programming/Functions

Page contents not supported in other languages.
Add topic
From Wikibooks, open books for an open world
Latest comment: 8 years ago by Dan Polansky in topic By Value and by Reference

Closure vs. nested function definition

[edit source]

I thought a closure was a more specific term than a nested function, specifically meaning a nested function that inherits some lexical bindings from the enclosing scope. Is it accurate to say that they are one and the same thing? --Fishpi (discusscontribs) 21:53, 23 February 2011 (UTC)Reply

I thought a closure was an inner function that is defined and returned by the outer function, but I'm still new to Python, so I may be wrong. But the definition given would include functions that use Yield to return the next iteration. I'm not sure those are considered closures. The example given is much more specific than the definition. We either need to refine the definition or come up with a more general example. --MiguelMunoz (discusscontribs) 19:30, 27 November 2012 (UTC)Reply

By Value and by Reference

[edit source]

Objects passed as arguments to functions are passed by reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory.

Uh, that's not what "pass-by-reference" means. A call/pass-by-reference strictly and solely means that the parameter will share the reference with the provided argument. That is, it means that even an assignment to another value will modify the original. Contrary to what the page currently says, it has nothing to do with mutability of the type.

Python, like most languages, is call-by-value, even when using what we sometimes (slightly incorrectly) call references. The 'value' being copied is effectively the address of the pointer (in Python, I suppose a copy of the object binding).

There's a really simple test one can always use to check if it's reasonable to think something is call-by-reference:

def foo(bar):
    bar=None

x=3
foo(x)
print x #Did I just annihilate x? If it's still 3, then it's call-by-value

And to be clear, it doesn't matter that it's a number. It could have been an object, a module, or whatever. 75.119.233.162 (discuss) 07:16, 11 March 2015 (UTC)Reply

Admittedly, on assignment, passed objects such as lists do not act like references, and this is made clear on the page at least by means of an example. However, on method invocation, passed mutable objects do act as mutable references. Thus, def extendList(list1, additionList): list1.extend(additionList) really works for the caller. --Dan Polansky (discusscontribs) 12:33, 18 March 2017 (UTC)Reply