I saw usages of these two phrases: global scope and global namespace. What is the difference between them?
A namespace is a mapping from names to objects . A scope is a textual region of a Python program where a namespace is directly accessible.
Global scope or global namespace scope is the outermost namespace scope of a program, in which objects, functions, types and templates can be defined. A name has global namespace scope if the identifier's declaration appears outside of all blocks, namespaces, and classes.
There are three types of Python namespaces- global, local, and built-in. It's the same with a variable scope in python. Also, the 'global' keyword lets us refer to a name in a global scope.
The global namespace contains any names defined at the level of the main program. Python creates the global namespace when the main program body starts, and it remains in existence until the interpreter terminates. Strictly speaking, this may not be the only global namespace that exists.
In C++, every name has its scope outside which it doesn't exist. A scope can be defined by many ways : it can be defined by namespace, functions, classes and just { }.
So a namespace, global or otherwise, defines a scope. The global namespace refers to using ::
, and the symbols defined in this namespace are said to have global scope. A symbol, by default, exists in a global namespace, unless it is defined inside a block starts with keyword namespace
, or it is a member of a class, or a local variable of a function:
int a; //this a is defined in global namespace //which means, its scope is global. It exists everywhere. namespace N { int a; //it is defined in a non-global namespace called `N` //outside N it doesn't exist. } void f() { int a; //its scope is the function itself. //outside the function, a doesn't exist. { int a; //the curly braces defines this a's scope! } } class A { int a; //its scope is the class itself. //outside A, it doesn't exist. };
Also note that a name can be hidden by inner scope defined by either namespace, function, or class. So the name a
inside namespace N
hides the name a
in the global namspace. In the same way, the name in the function and class hides the name in the global namespace. If you face such situation, then you can use ::a
to refer to the name defined in the global namespace:
int a = 10; namespace N { int a = 100; void f() { int a = 1000; std::cout << a << std::endl; //prints 1000 std::cout << N::a << std::endl; //prints 100 std::cout << ::a << std::endl; //prints 10 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With