Nonlocal Keyword
Similar to the global keyword, Python also allows nonlocal names to be accessed within functions. To use the keyword, type nonlocal followed by the variable name. When using more than one variable, use a comma. Let us learn how to use nonlocal keywords with the help of a code.
def my_message():
message = "Hey Programmers!" # A nonlocal variable
def nested():
nonlocal message # Declare var as nonlocal
nested()
print(message)
my_message()
OUTPUT:
Hey Programmers!
Copy Code
LEGB Rule
LEGB is an abbreviation for (Local Enclosing Global Built-in) followed by the Python interpreter when executing a code.
The LEGB rule in Python is a name searching algorithm where Python looks up scopes in a particular order. For instance, if you want to look up a reference name, Python will look after all the scopes following the LEGB rule. That means, the interpreter will look for local scope, then global scope, followed by enclosing tag and then finally looking into built-in scopes. If the name is not present on either of the four scopes, you will perhaps get an error.
Using Scope Related Built-In Functions
Python Built-in functions relate to Python scope and namespace. The most commonly used scopes are globals(), locals(), dirs(), and vars(), to name a few . These functions make it easy to fetch information about a Python scope or namespace. As they are built-in, they are available for free and you do not need to fetch from any library or import from a module.
globals()
The globals() function relates to the scope and namespaces in Python. It updates and returns a dictionary representing the current global symbol table. When you call globals() within a function block, names that can be accessed globally from the function will be returned. Let us understand globals() with the help of a code.
score = 23
globals()['score'] = 10
print('The Score is:', score)
OUTPUT:
The Score is: 10
Copy Code
Dostları ilə paylaş: |