- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Namespaces and Scoping in Python
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money
- Namespaces and Scope in Python
- How will you compare namespaces in Python and C++?
- What is difference between builtin and globals namespaces in Python?
- How will you compare modules, classes and namespaces in Python?
- Lexical Scoping in Dart Programming
- What are Python namespaces all about?
- What are the basic scoping rules for python variables?
- PHP Namespaces Overview
- PHP Using namespaces
- How will you explain Python namespaces in easy way?
- How to generate XML documents with namespaces in Python?
- What are namespaces in C#?
- PHP Aliasing/Importing namespaces
- PHP Declaring sub-namespaces