简体   繁体   中英

why is python global scope affected by local scope operations?

I thought that changes to variables passed to a python function remain in the function's local scope and are not passed to global scope. But when I wrote a test script:

#! /usr/bin/python
from numpy import *

def fun(box, var):
    box[0]=box[0]*4
    var=var*4
    return 0

ubox,x = array([1.]), 1.
print ubox,x
fun(ubox,x)
print ubox,x

The output is:

[myplay4]$ ./temp.py 
[ 1.] 1.0
[ 4.] 1.0

The integer variable x is not affected by the operation inside the function but the array is. Lists are also affected but this only happens if operating on list/array slices not on individual elements.

Can anyone please explain why the local scope passes to global scope in this case?

In your function

def fun(box, var):
    box[0]=box[0]*4
    var=var*4
    return 0

both box and var are local, and changing them does not change their value in the calling scope. However, this line:

box[0]=box[0]*4

does not change box ; it changes the object that box refers to. If that line were written as

box = box[0]*4 + box[1:]

then box in calling scope would indeed remain unchanged.

The important thing to realize is that when pass an object to a function, the function does not work with an independent copy of that object, it works with the same object. So any changes to the object are visible to the outside.

You say that changes to local variables remain local. That's true, but it only applies to changing variables (ie reassigning them). It does not apply to mutating an object that a variable points to.

In your example, you reassign var , so the change is not visible on the outside. However you're mutating box (by reassigning one of its elements). That change is visible on the outside. If you simply reassigned box to refer to a different object ( box = something ), that change would not be visible on the outside.

This has nothing to do with scope at all.

You're passing an object into a function. Inside that function, that object is mutated. The point is that the variable inside the function refers to the same object as in the calling function, so the changes are visible outside.

This does not depend on scope. It depends on how Python copies objects. For this respect, there are three kind of objects: scalars, mutable objects, immutable objects.

Scalars are copied by value, mutable objects are copied by reference and immutable objects are probably copied by reference but since you cannot modify them there is no implication.

Scalars are fore example all numeric types. Immutable are: strings and tuple. Mutable are: lists, dictionaries and other objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM