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

Steven D'Aprano steve at pearwood.info
Mon Dec 9 12:47:07 CET 2013


On Mon, Dec 09, 2013 at 10:16:30AM +0530, Varuna Seneviratna wrote:

> 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?. 

Mostly right. Only one function can be called "abs" in the built-in 
names at the one time. You can (but you shouldn't!) change that 
function, so it is not necessarily the "abs" function that you expect. 
Nevertheless, the basic idea is okay.


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

When Python sees the code "abs(x)", it needs to know which function to 
call. The name "abs" alone isn't a function. There needs to be some sort 
of connection, some link, between the name "abs" and the function which 
returns the absolute value. That is what is called a mapping.

Likewise, the name "x" isn't a number. There needs to be a link, a 
mapping, between the name "x" and some value like 23 or -17.

Both functions and data values (like numbers and strings) are objects, 
so instead of saying "a mapping between names and functions or numbers 
or strings or lists or ..." we just say "between names and objects".

When Python sees a name, say, "spam", it first looks in the *local* 
namespace for a variable called "spam". If there is no such variable, it 
then looks in the *global* namespace, and if still not found it looks in 
the built-in namespace. Finally if still not found it raises NameError.

(I have simplified a little bit, but not too much.)

Does this help?



-- 
Steven


More information about the Tutor mailing list