Namespaces

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: local variable 'a' referenced before assignment

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: local variable 'CONSTANT' referenced before assignment
  1. Fix add_squared_constant() so it works to return [8, 16, 46] given data.

  2. Fix, without using the global keyword, so it works to return [8, 16, 46] given data.

  3. Fix, using the global keyword, so it works to return [8, 16, 46] given data. What happens to the global variable CONSTANT [2]?