Munch Lab

Scope rules in Python

Scope rules

When Python is needs a variable, say x, because it is going to evaluate an expression x is part of, it looks for a place where x has been defined. Defining a variable is what you do when you assign a value to it:

x = 4
x = y
x = function(a, b)

The same goes for functions. Say you have a functions and these are defined – when you have defined them:

def x():
    some code...

If all variables and functions were visible from anywhere in your code it would be simple. But for good reason, variables can be private – or local – to the context they are defined in. In other worlds, the “visibility” or “availability” of a variables and functions depends on where they are defined. This “visibility” is is called scope. Python has a prioritized list of contexts it goes through to find a variable or function name such as x called the LEGB Rule. (As you will see this rule covers topics we have not covered in the course yes, but it give here for reference through the course)

L: Local, Names assigned in any way within a function.

E. Enclosing, Names in any and all enclosing (nested) functions, form inner to outer.

G. Global, Names assigned at the top-level of a module (the file).

B. Built-in, Names of built-in function that come with Python like open,range,…

So, in the case of

def function():
    x = 'x is defined in function'
    print x
    def nested_function():
        x = 'x is defined in nested function'
        print x
    nested_function()

x = 'x is globally defined'

print x

function()

L : local, in the current function defined by def, e.g. nested_function.

E : Enclosed function, e.g. in the function nested_function in which the function function was defined.

G : Global, the code that is not inside a function.

B : Any builtin x in Python, if such a thing were to exist (luckily, the name x is not reserved :-)).

Try to play around with the code. What gets printed if you “comment out” some of the definitions of x like this so that python ignores those lines:

def function():
    x = 'x is defined in function'
    print x
    def nested_function():
#        x = 'x is defined in nested function'
        print x
    nested_function()

x = 'x is globally defined'

print x

function()

Interactive code examples

I have made a series of interactive examples of python code you can study to get an impression of how variables can be private to functions (i.e. local (L) vs. Global (G)).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: