Python Scope Example

February 20, 2009

Wow I just learnt a new thing about Python’s scope! Below are two examples.

1:

x = 1
def foo():
    print x
foo()

2:

x = 1
def foo():
    print x
    x = 2
foo()

Code snippet number 1 works. It looks up the variable x in its global namespace and prints it. Easy!

Code snippet number 2 breaks on line 3, because there’s an x defined in the function’s local namespace (even though it comes later) and so it knows that x is local and hence barfs when you try to print it before assigning it a value!

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: