Namespace

Last updated

In computing, 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.

Contents

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. [1] Some programming languages organize their variables and subroutines in namespaces. [2] [3] [4] Computer networks and distributed systems assign names to resources, such as computers, printers, websites, and remote files. Operating systems 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, 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:

<table><tr><td>Apples</td><td>Oranges</td></tr></table>

This XML carries information about a table (i.e. a piece of furniture):

<table><name>MahoganyCoffeeTable</name><width>80</width><length>120</length></table>

If these XML fragments were added together, there would be a name conflict. Both contain a <table>...</table> 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.

<h:table><h:tr><h:td>Apples</h:td><h:td>Oranges</h:td></h:tr></h:table><f:table><f:name>MahoganyCoffeeTable</f:name><f:width>80</f:width><f:length>120</f:length></f:table>

Naming system

A name in a namespace consists of a namespace name and a local name. [5] [6] The namespace name is usually applied as a prefix to the local name.

In augmented Backus–Naur form:

name=<namespacename>separator<localname> 

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

Examples of names in a namespace
ContextNameNamespace nameLocal name
Path /home/user/readme.txt/home/user (directory)readme.txt (file name)
Domain name www.example.comexample.com (domain name)www (leaf domain name)
C++ std::arraystd (C++ namespace)array (struct)
UN/LOCODE US NYCUS (country or territory)NYC (locality)
XML xmlns:xhtml="http://www.w3.org/1999/xhtml"
<xhtml:body>
xhtml (previously declared XML namespace xhtml="http://www.w3.org/1999/xhtml")body (element)
Perl $DBI::errstr$DBI (Perl module)errstr (variable)
Java java.util.Datejava.util (Java namespace)Date (class)
Uniform Resource Name (URN) urn:nbn:fi-fe19991055 urn:nbn (National Bibliography Numbers)fi-fe19991055
Handle System 10.1000/18210 (handle naming authority)1000/182 (handle local name)
Digital object identifier 10.1000/18210.1000 (publisher)182 (publication)
MAC address 01-23-45-67-89-ab01-23-45 (organizationally unique identifier)67-89-ab (NIC specific)
PCI ID 1234 abcd1234 (vendor ID)abcd (device ID)
USB VID/PID 2341 003f [7] 2341 (vendor ID)003f (product ID)
SPARQL dbr:Sydneydbr (previously declared ontology, e.g. by specifying @prefix dbr: <http://dbpedia.org/resource/>)Sydney

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. [8] 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 (IANA) number.

Hierarchical namespace breakdown for urn:isbn:978-3-16-148410-0, an identifier for the book The Logic of Scientific Discovery by Karl Popper, 10th edition.
RegistryRegistrarExample IdentifierNamespace nameNamespace
Uniform Resource Name (URN) Internet Assigned Numbers Authority urn:isbn:978-3-16-148410-0 urn Formal URN namespace
Formal URN namespace Internet Assigned Numbers Authority urn:isbn:978-3-16-148410-0 ISBN International Standard Book Numbers as Uniform Resource Names
International Article Number (EAN) GS1 978-3-16-148410-0978 Bookland
International Standard Book Number (ISBN) International ISBN Agency 3-16-148410-X3 German-speaking countries
German publisher code Agentur für Buchmarktstandards 3-16-148410-X 16 Mohr Siebeck

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.

Examples of naming systems with local and global scope, and with and without namespaces
Without a namespaceWith a namespace
Local scope Vehicle registration plate Filesystem Hierarchy Standard
Global scope Universally unique identifier Domain Name System

In programming languages

For many programming languages, namespace is a context for their identifiers. In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. [9]

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, because the same name in different namespaces can have different meanings, each one appropriate for its namespace.

Following are other characteristics of namespaces:

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<iostream>// This is how one brings a name into the current scope.  In this case, it's// bringing them into global scope.usingstd::cout;usingstd::endl;namespacebox1{intbox_side=4;}namespacebox2{intbox_side=12;}intmain(){intbox_side=42;cout<<box1::box_side<<endl;// Outputs 4.cout<<box2::box_side<<endl;// Outputs 12.cout<<box_side<<endl;// Outputs 42.}

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 identifiers or symbols (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. [10]

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 programs 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 devices and many modern programming languages 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. 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.cstaticint_add(inta,intb){returna+b;}conststruct{doublepi;int(*add)(int,int);}helper={3.14,_add};// helper.hconststruct{doublepi;int(*add)(int,int);}helper;// main.c#include<stdio.h>#include"helper.h"intmain(){printf("3 + 2 = %d\n",helper.add(3,2));printf("pi is %f\n",helper.pi);}
C++

In C++, a namespace is defined with a namespace block. [11]

namespaceabc{intbar;}

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

usingnamespaceabc;

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.

intfoo;

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 collisions. 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 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, the idea of a namespace is embodied in Java packages. 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—the package java.lang contains classes core to the language, and java.lang.reflect 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 and class scopes can be viewed as implicit namespaces that are inextricably linked with visibility, accessibility, and object lifetime.

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 collisions. 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!");inti=System.Convert.ToInt32("123");

or add a using statement. This, eliminates the need to mention the complete name of all classes in that namespace.

usingSystem;Console.WriteLine("Hello World!");inti=Convert.ToInt32("123");

In the above examples, System is a namespace, and Console and Convert are classes defined within System.

Dotnet-system-namespace-uml.svg

Python

In Python, namespaces are defined by the individual modules, and since modules can be contained in hierarchical packages, then namespaces are hierarchical too. [12] [13] 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 : Class1importModuleaModulea.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 : Class1fromModuleaimportfunc1func1()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. [14]

Python also supports import x as y as a way of providing an alias or alternative name for use by the calling module:

importnumpyasnpa=np.arange(1000)
XML namespace

In XML, 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 from version 5.3 onwards. Naming collision of classes, functions and variables can be avoided. In PHP, a namespace is defined with a namespace block.

# File phpstar/foobar.phpnamespacephpstar;classFooBar{publicfunctionfoo():void{echo'Hello world, from function foo';}publicfunctionbar():void{echo'Hello world, from function bar';}}

We can reference a PHP namespace with the following different ways:

# File index.php# Include the fileinclude"phpstar/foobar.php";# Option 1: directly prefix the class name with the namespace$obj_foobar=new\phpstar\FooBar();# Option 2: import the namespaceusephpstar\FooBar;$obj_foobar=newFooBar();# Option 2a: import & alias the namespaceusephpstar\FooBarasFB;$obj_foobar=newFB();# Access the properties and methods with regular way$obj_foobar->foo();$obj_foobar->bar();

UML phpstar package diagram.svg

Emulating namespaces

In programming languages lacking language support for namespaces, namespaces can be emulated to some extent by using an identifier naming convention. For example, C libraries such as libpng 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 provides reasonable assurance that the identifiers are unique and can therefore be used in larger programs without naming collisions. [15] Likewise, many packages originally written in Fortran (e.g., BLAS, LAPACK) reserve the first few letters of a function's name to indicate which group it belongs to.

This technique has several drawbacks:

There are several advantages:

See also

Related Research Articles

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

A Perl module is a discrete component of software for the Perl programming language. Technically, it is a particular set of conventions for using Perl's package mechanism that has become universally adopted.

In compiler construction, name mangling is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

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.

In object-oriented programming, a destructor is a method which is invoked mechanically just before the memory of the object is released. It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded in another object whose lifetime ends, or when it was allocated dynamically and is released explicitly. Its main purpose is to free the resources which were acquired by the object during its life and/or deregister from other entities which may keep references to it. Use of destructors is needed for the process of Resource Acquisition Is Initialization (RAII).

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 computer language design, stropping is a method of explicitly marking letter sequences as having a special property, such as being a keyword, or a certain type of variable or storage location, and thus inhabiting a different namespace from ordinary names ("identifiers"), in order to avoid clashes. Stropping is not used in most modern languages – instead, keywords are reserved words and cannot be used as identifiers. Stropping allows the same letter sequence to be used both as a keyword and as an identifier, and simplifies parsing in that case – for example allowing a variable named if without clashing with the keyword if.

Haxe is a high-level cross-platform programming language and compiler that can produce applications and source code for many different computing platforms from one code-base. It is free and open-source software, released under the MIT License. The compiler, written in OCaml, is released under the GNU General Public License (GPL) version 2.

This comparison of programming languages compares the features of language syntax (format) for over 50 computer programming languages.

The Java Platform Module System specifies a distribution format for collections of Java code and associated resources. It also specifies a repository for storing these collections, or modules, and identifies how they can be discovered, loaded and checked for integrity. It includes features such as namespaces with the aim of fixing some of the shortcomings in the existing JAR format, especially the JAR Hell, which can lead to issues such as classpath and class loading problems.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

In computer science, marshalling or marshaling is the process of transforming the memory representation of an object into a data format suitable for storage or transmission, especially between different runtimes. It is typically used when data must be moved between different parts of a computer program or from one program to another.

Many programming languages and other computer files have a directive, often called include, import, or copy, that causes the contents of the specified file to be inserted into the original file. These included files are called header files or copybooks. They are often used to define the physical layout of program data, pieces of procedural code, and/or forward declarations while promoting encapsulation and the reuse of code or data.

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

In computer programming, a fully qualified name is an unambiguous name that specifies which object, function, or variable a call refers to without regard to the context of the call. In a hierarchical structure, a name is fully qualified when it "is complete in the sense that it includes (a) all names in the hierarchic sequence above the given element and (b) the name of the given element itself."

<span class="mw-page-title-main">Nim (programming language)</span> Programming language

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

In programming languages, name resolution is the resolution of the tokens within program expressions to the intended program components.

References

  1. Adya, Atul; Bolosky, William; Castro, Miguel; Cermak, Gerald; Chaiken, Ronnie; Douceur, John; Howell, Jon; Lorch, Jacob; Theimer, Marvin; Wattenhofer, Roger (2002). FARSITE: Federated, Available, and Reliable Storage for an Incompletely Trusted Environment (PDF). Proc. USENIX Symp. on Operating Systems Design and Implementation. Archived from the original (PDF) on 2010-07-28. The primary construct established by a file system is a hierarchical directory namespace, which is the logical repository for files.
  2. "C# FAQ: What is a namespace". C# Online Net. Archived from the original on 2013-10-20. Retrieved 2010-02-23. A namespace is nothing but a group of assemblies, classes, or types. A namespace acts as a container—like a disk folder—for classes organized into groups usually based on functionality. C# namespace syntax allows namespaces to be nested.
  3. "An overview of namespaces in PHP". PHP Manual. What are namespaces? In the broadest definition, namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them.
  4. "Creating and Using Packages". Java Documentation. Oracle. A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.[ better source needed ]
  5. XML Core Working Group (8 December 2009). "Namespaces in XML 1.0 (Third Edition)". W3C. Retrieved 2012-03-30.
  6. Moats, Ryan (May 1997). "Syntax". URN Syntax. IETF. p. 1. sec. 2. doi: 10.17487/RFC2141 . RFC 2141 . Retrieved 2012-03-30.
  7. Stephen J. Gowdy. "List of USB ID's". 2013.
  8. Sollins & Masinter (December 1994). "Requirements for functional capabilities". Functional Requirements for Uniform Resource Names. IETF. p. 3. sec. 2. doi: 10.17487/RFC1731 . RFC 1731 . Retrieved 2012-03-30.
  9. "C# FAQ: What is a namespace". C# Online Net. Archived from the original on October 20, 2013. Retrieved 2010-02-23. For instance, [under Windows], to access the built-in input-output (I/O) classes and members, use the System.IO namespace. Or, to access Web-related classes and members, use the System.Web namespace.
  10. "A namespace is "a logical grouping of the names used within a program."". Webopedia.com. 10 April 2002. Retrieved 2011-07-26.
  11. "Namespaces allow to group entities like classes, objects and functions under a name". Cplusplus.com. Retrieved 2011-07-26.
  12. "6. Modules". The Python Tutorial. Python Software Foundation. Retrieved 25 October 2010.
  13. "Python Scopes and Namespaces". Docs.python.org. Retrieved 2011-07-26.
  14. https://docs.python.org/3/tutorial/modules.html "in general the practice of importing * from a module or package is frowned upon"
  15. Danny Kalev. "Why I Hate Namespaces". Archived from the original on 2016-07-09.{{cite web}}: CS1 maint: bot: original URL status unknown (link)