Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Namespace
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===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]]s or [[symbol]]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.<ref>{{cite web |url=http://www.webopedia.com/TERM/N/namespace.html |title=A namespace is "a logical grouping of the names used within a program."|date=10 April 2002 | publisher=Webopedia.com| access-date=2011-07-26}}</ref> 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]]s or documents it is common to have hundreds or thousands of identifiers. Namespaces (or a similar technique, see [[#Emulating namespaces|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 [[modularity (programming)|modular]]. [[Data storage device]]s and many modern [[programming language]]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 (programming language)|Python]]), the identifiers naming namespaces are themselves associated with an enclosing namespace. Thus, in these languages namespaces can nest, forming a namespace [[tree (data structure)|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 (programming language)|C]] since [[C99]]. <syntaxhighlight lang="c"> // helper.c static int _add(int a, int b) { return a + b; } const struct { double pi; int (*add) (int, int); } helper = { 3.14, _add }; // helper.h const struct { double pi; int (*add) (int, int); } helper; // main.c #include <stdio.h> #include "helper.h" int main(){ printf("3 + 2 = %d\n", helper.add(3, 2)); printf("pi is %f\n", helper.pi); } </syntaxhighlight> =====C++===== In [[C++]], a namespace is defined with a namespace block.<ref>{{cite web|url=http://www.cplusplus.com/doc/tutorial/namespaces/ |title=Namespaces allow to group entities like classes, objects and functions under a name. |publisher=Cplusplus.com |access-date=2011-07-26}}</ref> <syntaxhighlight lang="cpp"> namespace abc { int bar; } </syntaxhighlight> 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 <code>namespace abc</code>, <code>bar</code> must be written <code>abc::bar</code> to be accessed. C++ includes another construct that makes this verbosity unnecessary. By adding the line <syntaxhighlight lang="cpp"> using namespace abc; </syntaxhighlight> to a piece of code, the prefix <code>abc::</code> is no longer needed. Identifiers that are not explicitly declared within a namespace are considered to be in the global namespace. <syntaxhighlight lang="cpp"> int foo; </syntaxhighlight> These identifiers can be used exactly as they are declared, or, since the global namespace is unnamed, the namespace specifier <code>::</code> can be prefixed. For example, <code>foo</code> can also be written <code>::foo</code>. Namespace resolution in C++ is hierarchical. This means that within the hypothetical namespace <code>food::soup</code>, the identifier <code>chicken</code> refers to <code>food::soup::chicken</code>. If <code>food::soup::chicken</code> doesn't exist, it then refers to <code>food::chicken</code>. If neither <code>food::soup::chicken</code> nor <code>food::chicken</code> exist, <code>chicken</code> refers to <code>::chicken</code>, an identifier in the global namespace. Namespaces in C++ are most often used to avoid [[naming collision]]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]] is defined within <code>namespace std</code>, but before standardization many components were originally in the global namespace. A programmer can insert the <code>using</code> 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 <code>using</code> directive for reasons other than backwards compatibility (e.g., convenience) is considered to be against good code practices. =====Java===== In [[Java (programming language)|Java]], the idea of a namespace is embodied in [[Java package]]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 <code>class String</code> in <code>package [[java.lang]]</code> can be referred to as <code>java.lang.String</code> (this is known as the [[fully qualified name|fully qualified class name]]). Like C++, Java offers a construct that makes it unnecessary to type the package name (<code>import</code>). However, certain features (such as [[reflection (computer science)|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 <code>java</code> are a part of the [[Java platform]]βthe package {{Javadoc:SE|package=java.lang|java/lang}} contains classes core to the language, and {{Javadoc:SE|package=java.lang.reflect|java/lang/reflect}} contains core classes specifically relating to reflection. In Java (and [[Ada (programming language)|Ada]], [[C Sharp (programming language)|C#]], and others), namespaces/packages express semantic categories of code. For example, in C#, <code>namespace System</code> 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 (programming)|Function]] and [[class (computer science)|class]] [[scope (programming)|scope]]s 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 collision]]s. When referencing a class, one should specify either its fully qualified name, which means namespace followed by the class name: <syntaxhighlight lang="c#"> System.Console.WriteLine("Hello World!"); int i = System.Convert.ToInt32("123"); </syntaxhighlight> or add a '''using''' statement. This eliminates the need to mention the complete name of all classes in that namespace. <syntaxhighlight lang="c#"> using System; Console.WriteLine("Hello World!"); int i = Convert.ToInt32("123"); </syntaxhighlight> In the above examples, '''System''' is a namespace, and '''Console''' and '''Convert''' are classes defined within '''System'''. [[File:Dotnet-system-namespace-uml.svg|UML diagram with a Console and a Convert class.]] =====Python===== In [[Python (programming language)|Python]], namespaces are defined by the individual modules, and since modules can be contained in hierarchical packages, then namespaces are hierarchical too.<ref>{{cite web|title=6. Modules|url=https://docs.python.org/tutorial/modules.html|work=The Python Tutorial|publisher=Python Software Foundation|access-date=25 October 2010}}</ref><ref>{{cite web|url=https://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces |title=Python Scopes and Namespaces |publisher=Docs.python.org |access-date=2011-07-26}}</ref> 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. <syntaxhighlight lang="python"> # assume modulea defines two functions : func1() and func2() and one class : Class1 import Modulea Modulea.func1() Modulea.func2() a = Modulea.Class1() </syntaxhighlight> The <code>from ... import ...</code> 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: <syntaxhighlight lang="python"> # 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() </syntaxhighlight> Since this directly imports names (without qualification) it can overwrite existing names with no warnings. A special form of the statement is <code>from ... import *</code> 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.<ref>https://docs.python.org/3/tutorial/modules.html "in general the practice of importing * from a module or package is frowned upon"</ref> Python also supports <code>import x as y</code> as a way of providing an alias or alternative name for use by the calling module: <syntaxhighlight lang="numpy"> import numpy as np a = np.arange(1000) </syntaxhighlight> ===== XML namespace <!-- This section is linked from [[XML]] --> ===== {{Main|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 <!-- This section is linked from [[PHP]] --> ===== Namespaces were introduced into [[Php|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. <syntaxhighlight lang="php"> # File phpstar/foobar.php namespace phpstar; class FooBar { public function foo(): void { echo 'Hello world, from function foo'; } public function bar(): void { echo 'Hello world, from function bar'; } } </syntaxhighlight> We can reference a PHP namespace with the following different ways: <syntaxhighlight lang="php"> # 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(); </syntaxhighlight> [[File:UML phpstar package diagram.svg|UML diagram of the phpstar package with the class FooBar.]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)