[Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

Amit Saha amitsaha.in at gmail.com
Mon Dec 9 12:27:58 CET 2013


On Mon, Dec 9, 2013 at 2:46 PM, Varuna Seneviratna
<varunaseneviratna at gmail.com> wrote:
>> Let’s begin with some definitions.
>>
>> A namespace is a mapping from names to objects. Most namespaces are
>> currently implemented as Python dictionaries, but that’s normally not
>> noticeable in any way (except for performance), and it may change in the
>> future. Examples of namespaces are: the set of built-in names (containing
>> functions such as abs(), and built-in exception names); the global names in
>> a module; and the local names in a function invocation. In a sense the set
>> of attributes of an object also form a namespace. The important thing to
>> know about namespaces is that there is absolutely no relation between names
>> in different namespaces; for instance, two different modules may both define
>> a function maximize without confusion — users of the modules must prefix it
>> with the module name.
>
>    The above paragraph was extracted from the description about namespaces
> from the Python tutorial(Python Scopes and Namespaces).I do not understand
> what is meant by "A namespace is a mapping from names to objects". How I
> understand to be a namespace is a particular space within which a particular
> name is unique.For a example within the space set of built-in names the name
> "abs()" is used to denote the function which returns the absolute value of a
> number and no other function(operation) can be named abs() as a built-in
> function.Am I right?.

You can name anything else as abs - a function, for example. But that
will override the built-in abs() function. For example:

>>> abs(1) # built-in abs
1
>>> def abs(num):
...     print('In my abs')
...
...
>>> abs(1)
In my abs


Similarly:

>>> abs = 1
>>> abs()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable


But what is meant by "A namespace is a mapping from
> names to objects"

I don't think I can explain this clearly enough to help elucidate the
literal meaning, so I hope somebody else will.

Best,
Amit.

-- 
http://echorand.me


More information about the Tutor mailing list