Functions Scope Namespace
Functions Scope Namespace
Ibrahim Abou-Faycal
#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Functions - Scope & Namespace
Reading: [Guttag, Sections 4.1,4.2, 4.5, and 5.3] Material in these slides is based on
• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 4]
• [MIT OpenCourseWare, 6.0001, Lecture 4, Fall 2016]
0.1 Namespace
• A namespace is kind of a “dictionary”
– It maps names (as strings) to values
– Executing the statement x = 3, mutates a namespace
– When executing the statement print(x), Python looks through a list of namespaces to
try and find one with the name x
– Actually it is technically precisely a dictionary; more on this later
0.2 Scope
• A scope defines which namespaces will be looked in and in what order
• The scope of any reference always starts in the local namespace, and moves outwards
until it reaches the module’s global namespace, before moving on to the builtins, which is
the end of the line
• A concise rule for Python Scope resolution: LEGB Rule
– Local — Names assigned in any way within a function (and not declared global in that
function)
– Enclosing-function — Names assigned in the local scope of any and all statically enclosing
functions (from inner to outer)
1
– Global (module) — Names assigned at the top-level of a module file (or by executing a
global statement in a def within the file)
– Built-in (Python) — Names preassigned in the built-in names module: open, range,
SyntaxError, etc
0.3 Return
• The return statement stops the execution of a function and assigns the returned value
• return is different from print, which only displays values
2
• Say that instead of defining x on Paper B, you simply read the value of x while working on
Paper B
• Does this make sense?
−→ YES: have read-only access
• Does it make sense to modify it later on?
−→ NO: too confusing
v = maxVal(3,7)
print(v)
http://www.pythontutor.com/visualize.html#mode=display
Visualize it
Get a stack of namespaces of: * depth 1: before calling maxVal3 * depth 2: right after calling
maxVal3 * depth 3: when maxVal3 calls maxVal on x and y * depth 2: when maxVal3 returns *
depth 3: when maxVal3 calls maxVal on a and z * depth 2: when maxVal returns * depth 1: when
maxVal3 returns
Note that x in maxVal3 and x in maxVal are not the same
3
4