reference vs. name space question

Ben Finney ben+python at benfinney.id.au
Sun Oct 10 01:00:37 EDT 2010


chad <cdalten at gmail.com> writes:

> 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

Because code that uses ‘spam’ as a reference was executed.

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

Because no names were used as references.

> I mean, in the first case, 'spam' isn't bound to anything.

Right, and yet you asked the Python interpreter to resolve it as a
reference. Hence the NameError.

> Likewise, in the second case, both 'x' and 'y' aren't bound to
> anything.

And nothing has yet asked the Python interpreter to resolve them as
references. Instead, you defined a function object and bound that object
to the name ‘foo’.

> I don't see why the interpreter doesn't complain about 'x' and 'y' not
> being defined.

I'd advise that you need to *do* (not just read, but actually perform)
the whole Python tutorial from start to finish, to get a good grounding
in concepts in a sensible order <URL:http://docs.python.org/tutorial/>.

-- 
 \       Moriarty: “Forty thousand million billion dollars? That money |
  `\            must be worth a fortune!” —The Goon Show, _The Sale of |
_o__)                                                       Manhattan_ |
Ben Finney



More information about the Python-list mailing list