15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

File "", line 3, in foo<br />

NameError: bar<br />

We will now define bar(), placing its declaration before foo() 's declaration:<br />

def bar():<br />

print 'in bar()'<br />

def foo():<br />

print 'in foo()'<br />

bar()<br />

Now we can safely call foo() with no problems:<br />

>>> foo()<br />

in foo()<br />

in bar()<br />

In fact, we can even declare foo() before bar():<br />

def foo():<br />

print 'in foo()'<br />

bar()<br />

def bar():<br />

print 'in bar()'<br />

Amazingly enough, this code still works fine with no forward referencing problems:<br />

>>> foo()<br />

in foo()<br />

in bar()<br />

This piece of code is fine because even though a call to bar() (from foo() ) appears before bar() 's<br />

definition, foo() itself is not called before bar() is declared. In other words, we declared foo(), then bar<br />

(), and then called foo(), but by that time, bar() existed already, so the call succeeds.<br />

Notice that the output of foo() succeeded before the error came about. NameError is the exception that<br />

is always raised when any uninitialized identifiers are accessed.<br />

11.3.4. Function Attributes<br />

We will briefly discuss namespaces later on in this chapter, especially their relationship to variable<br />

scope. There will be a more in-depth treatment of namespaces in the next chapter; however, here we<br />

want to point out a basic feature of <strong>Python</strong> namespaces.<br />

You get a free one with every <strong>Python</strong> module, class, and function. You can have a variable named x in

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!