Scoping Functions

Jed Rembold & Fred Agbo

February 19, 2024

Announcements

  • Project Wordle is due today at 10 pm.
  • Grading for PS3 will be returned this week! Apologies for the delay
  • We are in Ch6 of the text this week, which is interactive graphics
  • Remember the 1st midterm exam is this Friday Feb 23 in this hall
    • I will provide more information about the exam right this morning
    • Those with accommodations with Testing Center should contact them to make arrangement NOW! and cc me in the email
  • Polling continues https://www.polleverywhere.com/agbofred203

Mystery word

  • Let us walk through this program and unravel what will be printed when the program complete execution.
def mystery (x):
    def enigma (s, t):
        t -= 2
        return s [::6] + s[t]
    y = len(x)
    z = x[1 - y]
    z += enigma (x, y)
    z += enigma (x, y - 2)
    return z

if __name__ == '__main__':
    print(mystery ("abcdefgh"))


Graphic function with default color

  • You can return any type of variable from a function, including GObject graphical objects
  • Can be useful to write simple functions that bundle together common tasks
    • For instance, to create a filled circle centered at some location:
def make_filled_circ(x_cent, y_cent, radius, color='black'):
    circle = GOval(x_cent-radius, y_cent-radius, 2*radius, 2*radius)
    circle.set_color(color)
    circle.set_filled(True)
    return circle

Summary of a Function Call

  1. Evaluate the arguments in the context of the caller
  2. Reserve space for the function in a new stack frame
  3. Copy each positional argument to the corresponding parameter variable
  4. Copy each keyword argument to the parameter with that name
  5. For parameters with default values, if not already assigned, assign those values
  6. Evaluate statements in the function body, using current stack frame to look up values of local variables
  7. On encountering a return, compute the return value and substitute that value in place of the function call
  8. Remove the stack frame
  9. Return to the caller, continuing from just after the function call

Name Resolution and Scope

  • When Python encounters a variable name in a program, it looks for where the variable was defined in an expanding search:
    1. Local - The local context is all the variables defined within the current function. This includes variables appearing as a parameter!
    2. Enclosing - The enclosing context consists of the names defined in a function enclosing the current one.
    3. Global - The global context consists of names defined outside of any function or imported into the current module.
    4. Built-in - The last place Python looks is in the names of any built-in functions, like abs, str, print, etc.
  • The part of a program in which a name is defined in called its scope

Scoping Example

def func1(x,y):
    return z + func2(x,y)

def func2(x,y):
    def func3(x):
        return (y + x) ** 2

    z = x - func3(y)
    return z - y

z = 1
print(func1(2,z))

Local Variables

  • In Python, assigning any value to a variable means that the variable is assumed to be local

    • This generally makes sense, as you would not want more specific functions overriding variables in other areas
  • Can lead to issues though:

    def increment():
      x = x + 1
    
    x = 0
    increment()
  • The variable x in the fuction is local within that scope, and another global x with value 0 can cause issues

Review Question!

What would be the printed value of z at the end of the code to the right?

  1. 19
  2. 25
  3. 27
  4. None of the above
def f(x,y=0):
    z = (x + 3) ** 2
    return y + z

x = 1
z = x + f(y=x,x=2)
print(z)

The Python Event Model

  • Graphical applications usually make it possible for the user to control the action of a program by using an input device such a mouse.
    • Programs supporting this type of control are called interactive programs.
  • User actions such as clicking the mouse are called events.
  • Programs that respond to events are said to be event driven.
  • User input does not generally occur at predictable times. As the events are not controlled by the program, they are said to be asynchronous.
  • In Python, you write a function that acts as a listener for a particular event type. When the event happens, the listener is called.

First Class Functions

  • Functions in Python are treated as data values just like anything else!
    • We will need to take advantage of this to write listener functions.
  • You can assign a function to a variable, pass it as a parameter, return it as a result, etc
  • Functions treated like any other data value are called first-class functions
  • To work with a function itself, you leave off the (). Including the parentheses is how you call the function!

A First Class Example

import math

def evaluate_numbers(func):
    print(func)
    print(func(0))
    print(func(2))
    print(func(10))

A = evaluate_numbers

A(math.sqrt)
A(math.exp)

Closures

Consider the code to the right.

  • Why does the line 12 not error?
    • Nothing named a should still exist when it is called!
  • Python Tutor
  • f2 must also keep track of any local variables!
  • The local variables that are included as part of a function are called its closure
b = 1
def f1(a):
    print(a)
    print(b)

    def f2():
        c = a + b
        return c * 3
    return f2 

f2 = f1(10) 
c = f2()

Mid-term test

  • Test will take place during the class time 0n Friday.
  • Those with accommodations should already contact the testing center and cc me.
  • Practice questions are posted on this week’s module
  • Basic things to keep in mind:
    • The test contain detailed information to guide on what to expect. Read it carefully
    • The exam is partially open, and thus you are free to utilize:
      • The text
      • Your notes
      • Class slides
      • Any past work you have done as part of sections, problem sets, or projects, provided it has been uploaded, and you access it through GitHub.

Mid-term test

  • You are allowed to use a computer for ease of typing and accessing the above resources,
  • You are prohibited from accessing and using any editor or terminal to run your code.
    • Visual Studio Code or any similar editor should never be open on your computer during this exam.
  • Additionally, you are prohibited from accessing outside internet resources beyond the webpages described above.
  • practice questions (2 at least) will be posted today and Wednesday
    • first practice questions would be sent in PDF
    • second practice questions would be on canvas
// reveal.js plugins