Tuesday, September 28, 2021

Python for Beginners: Python Scope

While programming in python, we have to deal with various constructs like variables, functions, modules, libraries, etc.  In several instances, it is possible that a variable name used at a place may also be used at a different place without having any relation to the previous definition. In this article on python scope, we will try to understand how the definition of the variables is handled by the python interpreter.

What is a scope in Python?

When we define a variable, a function or a class name in a program, It is accessible in only a certain region of the program. This certain region in which a name, once defined, can be used to identify an object, a variable or a function is called scope.  The scope may extend from a single block of code like a function to the entire runtime environment depending on the definition of variable or function names.  

The concept of scope is closely related to namespaces and scopes are implemented as namespaces. We can consider a namespace as a python dictionary that maps object names to objects. The keys of the dictionary correspond to the names and the values correspond to the objects in python.

In python, there are four types of scope definitions, namely in-built scope, global scope,local scope and enclosing scope. We will study about all of these in the following sections.

What is the in-built scope in Python?

The built-in scope in python contains built-in object and function definitions. It is implemented using the builtins module in recent versions of python. 

Whenever we start the python interpreter, the builtins module is automatically loaded into our runtime environment. As a result, we can access all the functions and objects defined in the module in our program without any need to import them.

The functions like print(),abs(),input(),int(), float(), string(),sum(),max(),sorted() and other similar functions which are not needed to be imported before being used are defined in the built-in scope. We can have a look at the functions and object definitions which are available in the built-in scope as follows.

builtin_names = dir(__builtins__)
for name in builtin_names:
    print(name)

Output:

ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
ModuleNotFoundError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
enumerate
eval
exec
exit
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
quit
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip

The built-in scope is created once the interpreter is loaded and is destroyed with the closing of the python interpreter. All the names defined in the builtins module are in the built-in scope of the program.

What is a global scope?

The python script in which we write our code is termed as __main__ module by the python interpreter. The scope associated with the __main__ module is termed as a global scope. 

For any python program, there can be only one global scope. The global scope is created once the program starts and gets destroyed with the termination of the python program.

We can understand the notion of global scope from the following program.

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2

    def print_sum():
        print(temp)

    return temp

In the above program, myNum1 and myNum2 are in the global scope of the program. Objects which are present in global scope are defined outside of any code block.

What is a local scope?

The local scope in a python program is defined for a block of code such as function. Each function in a python program has its own local scope in which all its variables  and object names are defined. 

The local scope of a function is loaded when the function is called by any other function. Once the function terminates, the local scope associated with it is also terminated.

To understand the concept of local scope, look at the following example.

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2

    def print_sum():
        print(temp)

    return temp

In the above program, variables num1, num2 and temp exist in the local scope of add() function. These names exists only till the function add() is being executed.

What is an enclosing scope in Python?

Whenever a function is defined inside any other function, the scope of the inner function is defined inside the scope of the outer function. Due to this, The scope of the outer function is termed as the enclosing scope of the inner function. 

We can access all the variable names in a function that has been defined in its enclosing scope. However, we cannot access the variable names inside the outer function which are defined in the inner function. This can be more clear from the following example.

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2

    def print_sum():
        print(temp)

    return temp

Here, the print_sum() function exists in the local scope of add() function. Due to this, the variable names num1, num2 and temp which are defined in add() function are accessible in the scope of print_sum() function.

Conclusion

In this article, we have studied the concept of scope in python. We have also studied different scope types and their examples. To read other python concepts such as list comprehension, stay tuned.

The post Python Scope appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...