Globals and Scope

Global Variables

A global variable is a variable defined--first assigned to-- in the 'main' part of a Python program. Such variables are said to have 'global' scope and can be accessed from any function.
 
A local variable is a variable defined within a function. Such variables are said to have local scope—they are known only to the function.
 
Functions can access global variables and modify them, though its considered poor programming practice (you should send them in as params).

Python's Scope Rules

When a variable is encountered in a function, Python checks to see if it has been defined locally. If it has not, Python will check to see if there is a global with that name.
 
                def func():   # read example
                    # ...
                    print x  # python will use global x if it exists
 
If a variable is assigned to, a local slot is created for it.
 
                def func():  # write example
                    # ...
                    x=7  # this creates a local variable named 'x' and ignores a global named 'x' even it it exists.

To write to a global variable within a function, you must use the 'global' statement.
 
                def func():   # how to write to a global
                    global x   # declares that 'x' here refers to the global variable 'x'.
                    x=7
                    x=x+1  # modifies global x
                
                x=57
                func()  # the global x will be modified in the function.

Consider the following program snippets. What is the result of each?
 
def f():
    x=10
 
x=5
f()
print x
 
*************
def f():
    print x
x = 5
f()
********
def f():
    global x
    x=10
x=5
f()
print x

 
*************
def f():
    x=x+1
x=5
f()
print x
 
************
def f():
 
    list.append(5)
 
list=[1,2,3,4]
f()
print list
 
*************
def f():
    list=[]
    list.append(5)
 
list=[1,2,3,4]
f()
print list

Modular Programming

From wikipedia:

Modular programming is a software design technique that increases the extent to which software is composed from separate parts, called modules. Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components.

We want to think of a function as a black-box with inputs and outputs. The function only looks at data that is sent within the parameters. It's affect (output) is its return value and modified parameters. Some even argue that the effect should be limited to just the return value (no side effects!)

With modular programming, a function should not access (read) or modify global variables directly. The caller should send everything needed as a parameter.
 
A function signature is the function name and formal parameter list
 
 def ezkjakljfa(p1,p2):     # this line is the function signature
        # a bunch of code...
        return res

If we assume a program has been written in a modular fashion, it allows us to assume certain things as we read the code. It allows us to look at a function call and have an idea of what data it works on without actually looking at the function. Consider the following client code:

 # main
  z=99
  x=3
  y=2
  result = ezkjakljfa(x,y)   # we assume no side effects
  print result

If I know the program is written in a modular fashion, I can assume, without having to examine the code with function ezkjakljfa, that:
  •  ezkjakljfa will only look at x and y and doesn't depend on the values/existence of any other variables.
  •  the only effect of ezkjakljfa is that 'result' might change, and
 
******************
Instructor Assignment:
Rewrite the function 'pow' without parameters, and show a main program calling it. Then change it to the correct way.
 
1. For the following, determine if the code is modular, evil (has side effects), or just doesn't work.

# a
     import random
    def generateSecret():
        secretCode=[] 
        i=0
        while i<4:
            color = random.randint(0,5)
            secretCode.append(colors[color])
            i=i+1
    # main function call to it
    colors=['r','b','g','p','y','b']
    generateSecret()
    print secretCode
 
# b
    import random
    def generateSecret():
       
        i=0
        while i<4:
            color = random.randint(0,5)
            secretCode.append(colors[color])
            i=i+1
 
    # main function call to it:
 
    colors=['r','b','g','p','y','b']
    secretCode=[]   
    generateSecret()
    print secretCode
 
# c
    import random
    def generateSecret():
        secretCode=[]
        i=0
        while i<4:
            color = random.randint(0,5)
            secretCode.append(colors[color])
            i=i+1
        return secretCode
 
    # main function call to it:
 
    colors=['r','b','g','p','y','b']
    secretCode = generateSecret()
    print secretCode
 
 2. Rewrite your Mastermind program using functions. Make sure there are no side-effects in your functions, other than parameters changing values.

Comments

Recent site activity