reference vs. name space question

chad cdalten at gmail.com
Sun Oct 10 00:00:45 EDT 2010


On Oct 9, 5:52 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sat, 09 Oct 2010 12:44:29 -0700, chad wrote:
> > Given the following...
>
> > [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.
> >>>> class foo:
> > ...   x = 1
> > ...   y = 2
> > ...
> >>>> one = foo()
> >>>> two = foo()
> >>>> print one
> > <__main__.foo instance at 0xb7f3a2ec>
> >>>> print two
> > <__main__.foo instance at 0xb7f3a16c>
> >>>> one.x
> > 1
>
> > Is 'one' a reference or a name space?  Also, in 'one.x'. would 'one'
> > be the name space?
>
> 'one' is a name. Since it is a bound name, it naturally refers to some
> object (in this case an instance of foo), which also makes it a reference.
>
> The object that 'one' is bound to is the namespace. The name itself is
> not -- the name itself comes *from* a namespace (in this case the global
> namespace).
>
> However, since people are lazy, and 98% of the time it makes no
> difference, and it is long and tedious to say "the object which the name
> 'one' is bound to is a namespace", people (including me) will often
> shorten that to "'one' is a namespace". But remember that when people use
> a name sometimes they're talking about the name itself and sometimes the
> object it is bound to:
>
>
>
> >>> x = 123  # x applies to the name 'x'.
> >>> print x  # x applies to the object the name is bound to
> 123
> >>> del x  # x applies to the name 'x'
>
> Not all names are references:
>
> >>> spam
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'spam' is not defined
>
> Since the name 'spam' is not bound to any object, it is not a reference.
> Likewise, given:
>
> def func(x, y):
>     pass
>
> the name 'func' is a name which is bound to a function object. The
> function object includes two names 'x' and 'y'. Since they're not bound
> to anything, they are not references *yet*, but when you call the
> function, they become (temporarily) bound.
>
> Hope this helps.

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
>>> def foo(x, y):
...   pass
...
>>>

Doesn't? 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.

Chad



More information about the Python-list mailing list