Class and Namespaces 05
Namespaces in Python:
Namespace(s) is/are available at most Object Oriented languages, the clear idea of Namespaces is to declare names to variables and attributes. Let me share some sample to understand it clearly.
Error-Code 04
counter = 0
def counting_function():
print("Start:: ", counter)
counter += 1
print("After Counter::", counter)
if __name__ == "__main__":
counting_function()
O/P
..
UnboundLocalError: local variable 'counter' referenced before assignment
Note: To address this NameSpace and scope of variable are applied.
"global" keyword prefix to counter variable. If you add global keyword out-side the NameSpace, will result to error, try and check it by self for understanding declaration errors.
Fixed Code 04
counter = 0
def counting_function():
global counter
print("Start:: ", counter)
counter = counter + 1
print("After Counter::", counter)
if __name__ == "__main__":
counting_function()
O/P
..
Start:: 0
After Counter:: 1
Fixed Code 04.1
global counter
def counting_function():
counter = + 1
print("After Counter::", counter)
O/P
..
After Counter:: 1
Note: From fixed code 04, if "counter = counter + 1" is ignored code works perfect, due to
assignment . Lets look on one more example.
Error-Code 05
gl_variable = 5
def namespace_function():
i_variable = 6
print("Global variable:: ", gl_variable)
print("NS variable:: ", i_variable)
def inner_function():
i_value = 7
print("Inner value::", i_value)
print("NS variable scope::",i_variable)
if __name__ == "__main__":
namespace_function()
#inner_function() -- NameError: name 'inner_function' is not defined
O/P
..
Global variable:: 5
NS variable:: 6
Note: A new approach of Namespace(s) declare to maintain the scope of variables in this suite/block of code.
inner_function() is not called from main will result to an Error, so we have to call inner_function from scope of namespace_function fix code follows.
Fixed Code 05
gl_variable = 5
def namespace_function():
i_variable = 6
print("Global variable:: ", gl_variable)
print("NS variable:: ", i_variable)
def inner_function():
i_value = 7
print("Inner value::", i_value)
print("NS variable scope::",i_variable)
inner_function()
if __name__ == "__main__":
namespace_function()
O/P
..
Global variable:: 5
NS variable:: 6
Inner value:: 7
NS variable scope:: 6
Namespace for inner_function() call-scope, is with in the parent function itself.
Comments
Post a Comment