gk7
gk7

Reputation: 155

Lexical Scoping in Python

I am learning Python and more specifically I am exploring the scoping rules.

I tried the following "experiment":

def increment(n): 
   n += 1 
   print(n)
   return n

n = 1 
increment(n) 
print(n) 

This piece of code outputs: 2 , 1. Should n't it output instead 2, 2 since the variable n is returned to the global environment?

Your advice will be appreciated.

Upvotes: 3

Views: 4795

Answers (2)

P. Wormer
P. Wormer

Reputation: 387

Consider the following modification of the snippet above:

def increment(n): 
   n[0] += 1 
   print(n[0])
   return n

n = [1] 
increment(n) 
print(n[0]) 

This prints 2, 2.

In many computer languages (among them Javascript) a difference is made between function parameters that are primitive (like the integers 1 and 2) or compound (like the one-element list n[0]). Usually primitives are passed by value (their values are copied to temporary variables internal to the function). Compound entities are usually not copied, but passed by reference (the address of the entity is passed and the entity is accessed from within the function). If I look at the output of the two code snippets above, it seems to me that Python makes that difference too.

PS After I wrote this I looked at a 2009 Stack Overflow question. A primitive entity is called in the most popular 2009 answer an immutable object and a compound entity is called a mutable object, otherwise my answer is in agreement with the older answer.

Upvotes: -2

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

You have two distinct variables (names) here: one lives in the global scope, the other is local to increment. Rebinding the local one in increment doesn't impact the global one, and the fact that increment returns it's own n has no impact on the global one either (the fact they have the same name is irrelevant). If you want to have the global n pointing to the value returned by increment(), you have to rebind it explicitely:

n = 1
print(n)
n = increment(n)
print(n)

Upvotes: 5

Related Questions