3 ms·
`f` behaves just like closure. It can even be assigned to a variable. def f(x): x = 2 # <- this `x` is the same `x` as in the argument, it can be access vi
by fny 4y ago
`f` behaves just like closure. It can even be assigned to a variable.
def f(x): x = 2 # <- this `x` is the same `x` as in the argument, it can be access via locals() internally
You can even assign `f`. For example, `function = f`.
Python is call by reference. Change my mind. `def f(x): x[0] = 1` will manipulate whatever object you pass to it.
- Jtsummers 4y agoIf Python were fully call by reference then: def g(y): y = 3 x = 10 g(x) x # => ?? If it's 3 then it's pass by reference here, if it's 10 it's pass by reference. Which is it? Additionally, for something to be a closure it has to close over something (an environment). What does `f` or `g` close over? Note that they aren't changing any environment, they are "merely" functions, not closures. Python does have closures, but those aren't examples of them. And being able to assign a function to a variable does not make a closure, or do you think that C has closures because it has function pointers?
- Jtsummers 4y agoOops: If it's 3 then it's pass by reference here, if it's 10 it's pass by value. Which is it? (Don't hit reply when you're rushing out the door.)
- kazinator 4y ago> Python is call by reference. Change my mind. No need to change your entire mind; just an incorrect definition of call-by-reference. Passing a value which has reference semantics isn't call-by-reference. Your f receives x by value. That value is a reference into a boxed object. The x[0] = 1 does not change x; it changes the boxed object. >>> def f(x): ... x[0] = 1 ... >>> a = [ 0, 2, 3 ] >>> b = a >>> f(a) >>> a is b True The f function can do nothing to make "a is b" false. Under pass-by-reference, assigning to x would do that. Under pass-by-reference, we can pass a reference to a, such that a can be replaced, without affecting b. "pass-by {whatever}" refers to the semantics of the parameter and what it receives from the argument expression, and how, not the semantics of the argument object/value.