5.35. Namespaces#
A fundamental concept in programming, most easily explained with reference to the Variable scope.
In brief, variables defined within the local scope (or local namespace) are only “available” within that scope. Variables defined within the global scope can be accessed within both the global and local scope.
a = 2
def foo():
b = 3
print(a + b)
foo()
5
But they cannot be modified within the local scope (unless you use the global
keyword [1]).
def foo2():
a = a + b
print(a)
foo2()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[2], line 5
2 a = a + b
3 print(a)
----> 5 foo2()
Cell In[2], line 2, in foo2()
1 def foo2():
----> 2 a = a + b
3 print(a)
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
5.36. Exercises#
Consider this broken code
CONSTANT = 2
def add_squared_constant(data_series):
"""adds squared constant to elements of data_series"""
CONSTANT = CONSTANT**2
result = [v + CONSTANT for v in data_series]
return result
data = [4, 12, 42]
sqd = add_squared_constant(data)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[3], line 10
7 return result
9 data = [4, 12, 42]
---> 10 sqd = add_squared_constant(data)
Cell In[3], line 5, in add_squared_constant(data_series)
3 def add_squared_constant(data_series):
4 """adds squared constant to elements of data_series"""
----> 5 CONSTANT = CONSTANT**2
6 result = [v + CONSTANT for v in data_series]
7 return result
UnboundLocalError: cannot access local variable 'CONSTANT' where it is not associated with a value
Fix
add_squared_constant()
so it works to return[8, 16, 46]
givendata
.Fix, without using the
global
keyword, so it works to return[8, 16, 46]
givendata
.Fix, using the
global
keyword, so it works to return[8, 16, 46]
givendata
. What happens to the global variableCONSTANT
[2]?
A part of the coding style guidelines I use is to use ALL CAPS for variables that are meant to be treated as constants.