In
computing
Computing is any goal-oriented activity requiring, benefiting from, or creating computer, computing machinery. It includes the study and experimentation of algorithmic processes, and the development of both computer hardware, hardware and softw ...
, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily
identified.
Namespaces are commonly structured as hierarchies to allow reuse of names in different contexts. As an analogy, consider a system of
naming of people where each person has a given name, as well as a family name shared with their relatives. If the first names of family members are unique only within each family, then each person can be uniquely identified by the combination of first name and family name; there is only one Jane Doe, though there may be many Janes. Within the namespace of the Doe family, just "Jane" suffices to unambiguously designate this person, while within the "global" namespace of all people, the full name must be used.
Prominent examples for namespaces include
file systems, which assign names to files.
Some
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s organize their
variables and
subroutines in namespaces.
Computer network
A computer network is a collection of communicating computers and other devices, such as printers and smart phones. In order to communicate, the computers and devices must be connected by wired media like copper cables, optical fibers, or b ...
s and
distributed systems assign names to resources, such as
computer
A computer is a machine that can be Computer programming, programmed to automatically Execution (computing), carry out sequences of arithmetic or logical operations (''computation''). Modern digital electronic computers can perform generic set ...
s,
printers,
website
A website (also written as a web site) is any web page whose content is identified by a common domain name and is published on at least one web server. Websites are typically dedicated to a particular topic or purpose, such as news, educatio ...
s, and remote files.
Operating system
An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ...
s can partition
kernel resources by isolated namespaces to support
virtualization containers.
Similarly,
hierarchical file systems organize files in directories. Each directory is a separate namespace, so that the directories "letters" and "invoices" may both contain a file "to_jane".
In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, namespaces are typically employed for the purpose of grouping symbols and identifiers around a particular functionality and to avoid
name collisions between multiple identifiers that share the same name.
In
networking, the
Domain Name System organizes websites (and other resources) into
hierarchical namespaces.
Name conflicts
Element names are defined by the developer. This often results in a conflict when trying to mix XML documents from different XML applications.
This XML carries
HTML table information:
This XML carries information about a
table (i.e. a piece of furniture):
Mahogany Coffee Table
80
120
If these XML fragments were added together, there would be a name conflict. Both contain a element, but the elements have different content and meaning.
An XML parser will not know how to handle these differences.
Solution via prefix
Name conflicts in XML can easily be avoided using a name prefix.
The following XML distinguishes between information about the HTML table and furniture by prefixing "h" and "f" at the beginning of the elements.
Apples
Oranges
Mahogany Coffee Table
80
120
Naming system
A name in a namespace consists of a namespace name and a local name. The namespace name is usually applied as a
prefix to the local name.
In
augmented Backus–Naur form:
name = separator
When local names are used by themselves,
name resolution is used to decide which (if any) particular name is alluded to by some particular local name.
Examples
Delegation
Delegation of responsibilities between parties is important in real-world applications, such as the structure of the World Wide Web. Namespaces allow delegation of identifier assignment to multiple name issuing organisations whilst retaining global uniqueness. A central
Registration authority registers the
assigned namespace names allocated. Each namespace name is allocated to an organisation which is subsequently responsible for the assignment of names in their allocated namespace. This organisation may be a name issuing organisation that
assign the names themselves, or another
Registration authority which further delegates parts of their namespace to different organisations.
Hierarchy
A naming scheme that allows subdelegation of namespaces to third parties is a hierarchical namespace.
A hierarchy is recursive if the syntax for the namespace names is the same for each subdelegation. An example of a recursive hierarchy is the
Domain name system.
An example of a non-recursive hierarchy are
Uniform Resource Name representing an
Internet Assigned Numbers Authority
The Internet Assigned Numbers Authority (IANA) is a standards organization that oversees global IP address allocation, Autonomous system (Internet), autonomous system number allocation, DNS root zone, root zone management in the Domain Name Syste ...
(IANA) number.
Namespace versus scope
A namespace name may provide context (
scope in computer science) to a name, and the terms are sometimes used interchangeably. However, the context of a name may also be provided by other factors, such as the location where it occurs or the syntax of the name.
In programming languages
For many programming languages, namespace is a context for their
identifiers
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, person, physical countable object (or class thereof), or physical mass ...
. In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory.
As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace. A namespace is also called a
context
In semiotics, linguistics, sociology and anthropology, context refers to those objects or entities which surround a ''focal event'', in these disciplines typically a communicative event, of some kind. Context is "a frame that surrounds the event ...
, because the same name in different namespaces can have different meanings, each one appropriate for its namespace.
Following are other characteristics of namespaces:
* Names in the namespace can represent objects as well as
concept
A concept is an abstract idea that serves as a foundation for more concrete principles, thoughts, and beliefs.
Concepts play an important role in all aspects of cognition. As such, concepts are studied within such disciplines as linguistics, ...
s, be the namespace a
natural or ethnic language, a
constructed language
A constructed language (shortened to conlang) is a language whose phonology, grammar, orthography, and vocabulary, instead of having developed natural language, naturally, are consciously devised for some purpose, which may include being devise ...
, the
technical terminology
Jargon, or technical language, is the specialized terminology associated with a particular field or area of activity. Jargon is normally employed in a particular Context (language use), communicative context and may not be well understood outside ...
of a profession, a
dialect
A dialect is a Variety (linguistics), variety of language spoken by a particular group of people. This may include dominant and standard language, standardized varieties as well as Vernacular language, vernacular, unwritten, or non-standardize ...
, a
sociolect
In sociolinguistics, a sociolect is a form of language ( non-standard dialect, restricted register) or a set of lexical items used by a socioeconomic class, profession, age group, or other social group.
Sociolects involve both passive acquisit ...
, or an artificial language (e.g., a
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
).
* In the
Java programming language
Java is a high-level, general-purpose, memory-safe, object-oriented programming language. It is intended to let programmers ''write once, run anywhere'' ( WORA), meaning that compiled Java code can run on all platforms that support Jav ...
, identifiers that appear in namespaces have a short (local) name and a unique long "qualified" name for use outside the namespace.
* Some compilers (for languages such as
C++) combine namespaces and names for internal use in the compiler in a process called ''
name mangling
In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.
It provides means to e ...
''.
As well as its abstract language technical usage as described above, some languages have a specific keyword used for explicit namespace control, amongst other uses. Below is an example of a namespace in C++:
#include
// This is how one brings a name into the current scope. In this case, it's
// bringing them into global scope.
using std::cout;
using std::endl;
namespace box1
namespace box2
int main()
Computer-science considerations
A namespace in computer science (sometimes also called a name scope) is an abstract container or environment created to hold a logical grouping of unique
identifier
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, person, physical countable object (or class thereof), or physical mass ...
s or
symbol
A symbol is a mark, Sign (semiotics), sign, or word that indicates, signifies, or is understood as representing an idea, physical object, object, or wikt:relationship, relationship. Symbols allow people to go beyond what is known or seen by cr ...
s (i.e. names). An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces. That is, an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace. Languages that support namespaces specify the rules that determine to which namespace an identifier (not its definition) belongs.
This concept can be illustrated with an analogy. Imagine that two companies, X and Y, each assign ID numbers to their employees. X should not have two employees with the same ID number, and likewise for Y; but it is not a problem for the same ID number to be used at both companies. For example, if Bill works for company X and Jane works for company Y, then it is not a problem for each of them to be employee #123. In this analogy, the ID number is the identifier, and the company serves as the namespace. It does not cause problems for the same identifier to identify a different person in each namespace.
In large
computer program
A computer program is a sequence or set of instructions in a programming language for a computer to Execution (computing), execute. It is one component of software, which also includes software documentation, documentation and other intangibl ...
s or documents it is common to have hundreds or thousands of identifiers. Namespaces (or a similar technique, see
Emulating namespaces) provide a mechanism for hiding local identifiers. They provide a means of grouping logically related identifiers into corresponding namespaces, thereby making the system more
modular.
Data storage device
Data ( , ) are a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted form ...
s and many modern
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s support namespaces. Storage devices use directories (or folders) as namespaces. This allows two files with the same name to be stored on the device so long as they are stored in different directories. In some programming languages (e.g.
C++,
Python), the identifiers naming namespaces are themselves associated with an enclosing namespace. Thus, in these languages namespaces can nest, forming a namespace
tree
In botany, a tree is a perennial plant with an elongated stem, or trunk, usually supporting branches and leaves. In some usages, the definition of a tree may be narrower, e.g., including only woody plants with secondary growth, only ...
. At the root of this tree is the unnamed global namespace.
Use in common languages
=C
=
It is possible to use anonymous structs as namespaces in
C since
C99.
// helper.c
static int _add(int a, int b)
const struct helper = ;
// helper.h
const struct helper;
// main.c
#include
#include "helper.h"
int main()
=C++
=
In
C++, a namespace is defined with a namespace block.
namespace abc
Within this block, identifiers can be used exactly as they are declared. Outside of this block, the namespace specifier must be prefixed. For example, outside of
namespace abc
,
bar
must be written
abc::bar
to be accessed. C++ includes another construct that makes this verbosity unnecessary. By adding the line
using namespace abc;
to a piece of code, the prefix
abc::
is no longer needed.
Identifiers that are not explicitly declared within a namespace are considered to be in the global namespace.
int foo;
These identifiers can be used exactly as they are declared, or, since the global namespace is unnamed, the namespace specifier
::
can be prefixed. For example,
foo
can also be written
::foo
.
Namespace resolution in C++ is hierarchical. This means that within the hypothetical namespace
food::soup
, the identifier
chicken
refers to
food::soup::chicken
. If
food::soup::chicken
doesn't exist, it then refers to
food::chicken
. If neither
food::soup::chicken
nor
food::chicken
exist,
chicken
refers to
::chicken
, an identifier in the global namespace.
Namespaces in C++ are most often used to avoid
naming collision
A naming collision is a circumstance where two or more identifiers in a given namespace or a given scope cannot be unambiguously resolved, and such unambiguous resolution is a requirement of the underlying system.
Example: XML element names
In ...
s. Although namespaces are used extensively in recent C++ code, most older code does not use this facility because it did not exist in early versions of the language. For example, the entire
C++ Standard Library
The C standard library, sometimes referred to as libc, is the standard library for the C programming language, as specified in the ISO C standard.ISO/ IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the origina ...
is defined within
namespace std
, but before standardization many components were originally in the global namespace. A programmer can insert the
using
directive to bypass namespace resolution requirements and obtain backwards compatibility with older code that expects all identifiers to be in the global namespace. However the use of the
using
directive for reasons other than backwards compatibility (e.g., convenience) is considered to be against good code practices.
=Java
=
In
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, the idea of a namespace is embodied in
Java package
A Java package organizes Java classes into namespaces,
providing a unique namespace for each type it contains.
Classes in the same package can access each other's package-private and protected members.
In general, a package can contain the fo ...
s. All code belongs to a package, although that package need not be explicitly named. Code from other packages is accessed by prefixing the package name before the appropriate identifier, for example
class String
in
package java.lang
can be referred to as
java.lang.String
(this is known as the
fully qualified class name). Like C++, Java offers a construct that makes it unnecessary to type the package name (
import
). However, certain features (such as
reflection) require the programmer to use the fully qualified name.
Unlike C++, namespaces in Java are not hierarchical as far as the syntax of the language is concerned. However, packages are named in a hierarchical manner. For example, all packages beginning with
java
are a part of the
Java platform
Java is a set of computer software and specifications that provides a software platform for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms fr ...
—the package contains classes core to the language, and contains core classes specifically relating to reflection.
In Java (and
Ada,
C#, and others), namespaces/packages express semantic categories of code. For example, in C#,
namespace System
contains code provided by the system (the
.NET Framework). How specific these categories are and how deep the hierarchies go differ from language to language.
Function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-orie ...
and
class
Class, Classes, or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used d ...
scopes can be viewed as implicit namespaces that are inextricably linked with visibility, accessibility, and
object lifetime
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
.
=C#
=
Namespaces are heavily used in C# language. All .NET Framework classes are organized in namespaces, to be used more clearly and to avoid chaos. Furthermore, custom namespaces are extensively used by programmers, both to organize their work and to avoid
naming collision
A naming collision is a circumstance where two or more identifiers in a given namespace or a given scope cannot be unambiguously resolved, and such unambiguous resolution is a requirement of the underlying system.
Example: XML element names
In ...
s.
When referencing a class, one should specify either its fully qualified name, which means namespace followed by the class name:
System.Console.WriteLine("Hello World!");
int i = System.Convert.ToInt32("123");
or add a using statement. This eliminates the need to mention the complete name of all classes in that namespace.
using System;
Console.WriteLine("Hello World!");
int i = Convert.ToInt32("123");
In the above examples, System is a namespace, and Console and Convert are classes defined within System.
=Python
=
In
Python, namespaces are defined by the individual modules, and since modules can be contained in hierarchical packages, then namespaces are hierarchical too.
In general when a module is imported then the names defined in the module are defined via that module's namespace, and are accessed in from the calling modules by using the fully qualified name.
# assume modulea defines two functions : func1() and func2() and one class : Class1
import Modulea
Modulea.func1()
Modulea.func2()
a = Modulea.Class1()
The
from ... import ...
statement can be used to insert the relevant names directly into the calling module's namespace, and those names can be accessed from the calling module without the qualified name:
# assume Modulea defines two functions : func1() and func2() and one class : Class1
from Modulea import func1
func1()
func2() # this will fail as an undefined name, as will the full name Modulea.func2()
a = Class1() # this will fail as an undefined name, as will the full name Modulea.Class1()
Since this directly imports names (without qualification) it can overwrite existing names with no warnings.
A special form of the statement is
from ... import *
which imports all names defined in the named package directly in the calling module's namespace. Use of this form of import, although supported within the language, is generally discouraged as it pollutes the namespace of the calling module and will cause already defined names to be overwritten in the case of name clashes.
Python also supports
import x as y
as a way of providing an alias or alternative name for use by the calling module:
import numpy as np
a = np.arange(1000)
= XML namespace
=
In
XML
Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
, the XML namespace specification enables the names of elements and attributes in an XML document to be unique, similar to the role of namespaces in programming languages. Using XML namespaces, XML documents may contain element or attribute names from more than one XML vocabulary.
= PHP
=
Namespaces were introduced into
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
from version 5.3 onwards. Naming collision of classes, functions and variables can be avoided.
In
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
, a namespace is defined with a namespace block.
# File phpstar/foobar.php
namespace phpstar;
class FooBar
We can reference a PHP namespace with the following different ways:
# File index.php
# Include the file
include "phpstar/foobar.php";
# Option 1: directly prefix the class name with the namespace
$obj_foobar = new \phpstar\FooBar();
# Option 2: import the namespace
use phpstar\FooBar;
$obj_foobar = new FooBar();
# Option 2a: import & alias the namespace
use phpstar\FooBar as FB;
$obj_foobar = new FB();
# Access the properties and methods with regular way
$obj_foobar->foo();
$obj_foobar->bar();
Emulating namespaces
In programming languages lacking language support for namespaces, namespaces can be emulated to some extent by using an
identifier naming convention
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation.
Reasons for using a nam ...
. For example,
C libraries such as
libpng
libpng is the official Portable Network Graphics (PNG) reference library (originally called pnglib). It is a platform-independent library that contains C functions for handling PNG images. It supports almost all of PNG's features, is extensible, ...
often use a fixed prefix for all functions and variables that are part of their exposed interface. Libpng exposes identifiers such as:
png_create_write_struct
png_get_signature
png_read_row
png_set_invalid
This
naming convention
A naming convention is a convention (generally agreed scheme) for naming things. Conventions differ in their intents, which may include to:
* Allow useful information to be deduced from the names based on regularities. For instance, in Manhatta ...
provides reasonable assurance that the
identifier
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, person, physical countable object (or class thereof), or physical mass ...
s are unique and can therefore be used in larger programs without
naming collision
A naming collision is a circumstance where two or more identifiers in a given namespace or a given scope cannot be unambiguously resolved, and such unambiguous resolution is a requirement of the underlying system.
Example: XML element names
In ...
s.
Likewise, many packages originally written in
Fortran (e.g.,
BLAS Blas is mainly a Spanish given name and surname, related to Blaise. It may refer to
Places
*Piz Blas, mountain in Switzerland
* San Blas (disambiguation)
People
* Ricardo Blas Jr. (born 1986) Judo athlete from Guam
* Blas Antonio Sáenz (fl. 18 ...
,
LAPACK
LAPACK ("Linear Algebra Package") is a standard software library for numerical linear algebra. It provides routines for solving systems of linear equations and linear least squares, eigenvalue problems, and singular value decomposition. It als ...
) reserve the first few letters of a function's name to indicate the group to which the function belongs.
This technique has several drawbacks:
* It doesn't scale well to nested namespaces; identifiers become excessively long since all uses of the identifiers must be
fully namespace-qualified;
* Individuals or organizations may use inconsistent naming conventions, potentially introducing unwanted obfuscation;
* Compound or "query-based" operations on groups of identifiers, based on the namespaces in which they are declared, are rendered unwieldy or unfeasible;
* In languages with restricted identifier length, the use of prefixes limits the number of characters that can be used to identify what the function does; this is a particular problem for packages originally written in
FORTRAN 77, which offered only 6 characters per identifier; for example, the name of the
BLAS Blas is mainly a Spanish given name and surname, related to Blaise. It may refer to
Places
*Piz Blas, mountain in Switzerland
* San Blas (disambiguation)
People
* Ricardo Blas Jr. (born 1986) Judo athlete from Guam
* Blas Antonio Sáenz (fl. 18 ...
function
DGEMM
indicates that it operates on double-precision floating-point numbers (
D
) and general matrices (
GE
), with only the last two characters (
MM
) showing what it actually does: matrix–matrix multiplication.
It also has a few advantages:
* No special software tools are required to locate names in source-code files; a simple program like
grep
grep is a command-line utility for searching plaintext datasets for lines that match a regular expression. Its name comes from the ed command g/re/p (global regular expression search and print), which has the same effect. grep was originally de ...
suffices;
* There are no namespace-related name conflicts;
* There is no need for name mangling, and thus no potential incompatibility problems.
See also
* 11-digit
delivery point
In a Mail, postal system, a delivery point (sometimes DP) is a single mailbox or other place at which mail is delivered. It differs from a address (geography), street address, in that each address may have several delivery points, such as an apart ...
ZIP code
*
Binomial nomenclature
In taxonomy, binomial nomenclature ("two-term naming system"), also called binary nomenclature, is a formal system of naming species of living things by giving each a name composed of two parts, both of which use Latin grammatical forms, altho ...
(genus-species in
biology
Biology is the scientific study of life and living organisms. It is a broad natural science that encompasses a wide range of fields and unifying principles that explain the structure, function, growth, History of life, origin, evolution, and ...
)
*
Chemical nomenclature
Chemical nomenclature is a set of rules to generate systematic name#In chemistry, systematic names for chemical compounds. The nomenclature used most frequently worldwide is the one created and developed by the International Union of Pure and Appli ...
*
Dewey Decimal Classification
The Dewey Decimal Classification (DDC) (pronounced ) colloquially known as the Dewey Decimal System, is a proprietary library classification system which allows new books to be added to a library in their appropriate location based on subject. ...
*
Digital object identifier
A digital object identifier (DOI) is a persistent identifier or handle used to uniquely identify various objects, standardized by the International Organization for Standardization (ISO). DOIs are an implementation of the Handle System; th ...
*
Domain Name System
*
Fourth wall
The fourth wall is a performance dramatic convention, convention in which an invisible, imaginary wall separates actors from the audience. While the audience can see through this "wall", the convention assumes the actors act as if they cannot. ...
*
Identity (object-oriented programming)
In object-oriented programming, analysis and design, object identity is the fundamental property of every object that it is distinct from other objects. Objects have identity are distinct even when they are otherwise indistinguishable, i.e. eq ...
*
Library of Congress Classification
The Library of Congress Classification (LCC) is a system of library classification developed by the Library of Congress in the United States, which can be used for shelving books in a library. LCC is mainly used by large research and academic li ...
*
Star catalogue
A star catalogue is an astronomical catalogue that lists stars. In astronomy, many stars are referred to simply by catalogue numbers. There are a great many different star catalogues which have been produced for different purposes over the year ...
s and
astronomical naming conventions
In ancient times, only the Sun and Moon, a few stars, and the most easily visible planets had names. Over the last few hundred years, the number of identified astronomical objects has risen from hundreds to over a billion, and more are discovered ...
*
Violation of abstraction level
*
XML namespace
XML namespaces are used for providing uniquely named elements and attributes in an XML document. They are defined in a W3C recommendation. An XML instance may contain element or attribute names from more than one XML vocabulary. If each vocabulary ...
*
Argument-dependent name lookup
References
{{DEFAULTSORT:Namespace
Naming conventions