Tuesday, 7 January 2020

The special variable __name__

dir():

print(dir())

"""output
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__'] """

Python provides in built function dir() which displays all the members of currently running the program or module.
Syntax:
dir()
dir(specified module name)

Example 2: to get the modules information
#f:/Programs/Modules/tes2.py
import cali
print(dir())
print(dir(cali))

"""output
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'cali'] ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'div', 'mul', 'sub']
>>>


Note: For every module/program Python interpreter adds some special members (ex: variables/functions/classes) automatically for internal use.

Based on our requirement we can access these member/properties in our program.

"""

__name__ (double underscore before and after)
Example code:
print(__name__)

Output:
__main__

Example 2:
#f:/Programs/Modules/tes2.py
def display():
    if __name__=='__main__':
        print("The code executed as a program")
    else:
        print("This prog executed as a module from some other program")
output:
The code executed as a program
Here name contains main variable
Example 3:
#F:/Programs/Modules/test2.py
def display():
    if __name__=='__main__':
        print("The code executed as a program")
    else:
        print("This prog executed as a module from some other program")
    
#Testing _name_
#F:/Programs/Modules/disp.py
import test2
test2.display()
"""
Note: __name__ contains test2
output
This prog executed as a module from some other program
"""

In c, c++, java main is the starting point of execution. For example  when you are working any project, it may have multiple modules, in those modules but there will be one module you will execute first.
For example this test2.py is the first module, first module name always is __main__(double underscore before main and after main)

For every python program, some members added internally, here __name__ is added internally. This variable __name__ stores information regarding whether the program is executed as an individual program or as a module.

·         If the program executed as an individual program then the value this variable __name__ is __main__.
·         If the program executed as module from some other program then the value of this variable __name__ is name of the module (i.e __name__=test2) where it is defined.


Note: So by using this __name__ variable we can identify whether the program executed directly or as a module



Related video: https://www.youtube.com/watch?v=DZpN8_7i9l8&feature=youtu.be

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...