InterviewSolution
| 1. |
How does Python differentiate between executable script and importable script? |
|
Answer» A Python script has .py extension and can have DEFINITION of class, function, constants, variables and even some executable code. Also, any Python script can be imported in another script using import keyword. However, if we import a module having certain executable code, it will automatically get EXECUTED even if you do not intend to do so. That can be avoided by identifying __name__ property of module. When Python is running in interactive mode or as a script, it sets the value of this special VARIABLE to '__main__'. It is the name of the scope in which top level is being executed. >>> __name__ '__main__'From within a script also, we find value of __name__ attribute is set to '__main__'. Execute the following script. #example.py print ('name of module:',__name__) C:\users>python example.py name of module: __main__However, for imported module this attribute is set to the name of the Python script. (excluding the extension .py) >>> import example >>> messages.__name__ 'example'If we try to import example module in test.py script as follows: #test.py import example print (‘name of module:’,__name__) output: c:\users>python test.py name of module:example name of module: __main__However we wish to prevent the print statement in the executable part of example.py. To do that, identify the __name__ property of the module. If it is __main__ then only the print statement will be executed if we modify example.py as below: #example.py if __name__==”__main__”: print (‘name of module:,__name__)Now the output of test.py will not show the name of the imported module. |
|