reference vs. name space question

Steven D'Aprano steve at
Sun Oct 10 09:06:12 CEST 2010

On Sat, 09 Oct 2010 21:00:45 -0700, chad wrote:

> Maybe I'm being a bit dense, but how something like
> [cdalten at localhost oakland]$ python
> Python 2.6.2 (r262:71600, May  3 2009, 17:04:44) [GCC 4.1.1 20061011
> (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or
> "license" for more information.
>>>> spam
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'spam' is not defined
> Generate an error, but something like

In this case, you have asked Python to look up the name 'spam'. Since 
spam has never been bound to any object, (no assignment spam=something 
has occurred) the lookup fails and Python raises an exception.

>>>> def foo(x, y):
> ...   pass
> ...
> Doesn't? 

Why should it fail? You haven't attempted to look up names x or y. You 
have executed a function definition statement, which creates a new 
function object taking two arguments named x and y. The names only exist 
in the function's local namespace, they can only be referenced from 
inside the function's local namespace, and since you haven't yet called 
the function, Python doesn't make any attempt to look up the names, and 
so there is no error.

If you do call the function, one of two things will happen:

(1) You do supply arguments for x and y, in which case the names will be 
bound and looking them up will succeed; or

(2) You don't supply arguments for x and/or y, and Python will raise 
TypeError before the function code is executed.

> I mean, in the first case, 'spam' isn't bound to anything.
> Likewise, in the second case, both 'x' and 'y' aren't bound to anything.
> I don't see why the interpreter doesn't complain about 'x' and 'y' not
> being defined.

If it did, it would make it a bit hard to write functions if you couldn't 
refer to formal parameters.


More information about the Python-list mailing list