Sunday, October 25, 2020

what is __name__

Python has a special builtin variables which are delimited by double under scores. These variables are evaluated at runtime of python program. We will discuss one such variable here that is __name__ . This variable produces different outputs when module is imported  vs when module is executed directly. This is an important feature of python helps writing the module functionality accordingly.

Here we will be reusing the code written in our Module chapter. Reusing this to demonstrate the functionality.

Paste the code into below module words_name.py


'''
    Module to read a text file and convert each word 
    first letter to CAPS.
'''

def readfile(fileName):
    '''
       Reads input file passed as an agrument process the data
       and prints capitalized words to console.
       Args:
            Takes fileName as an argument
    '''
    fp = open(fileName, mode='rt', encoding='utf-8')
    words = fp.read().split()
    newWords = convertToCaps(words)
    print('Words in Capitalized form')
    for word in newWords:
        print (word)
    fp.close()
    

def convertToCaps(wordsList):
    '''
       Reads input fila passed as an agrument process the data
       and prints capitalized words to console.
       Args:
            Takes wordsList as an argument
       Returns:
            returns wordsList with capitalized letter in each word
    '''
    capitalizedWords = []
    for word in wordsList:
        capitalizedWords.append(word.capitalize())
    return capitalizedWords
    
    
print(__name__) # Using the double under score variable

In the last line of above code we are outputting the value of __name__ variable.

Importing the Module
Here we imported the module, output of the __name__ variable is evaluated to module name words_name

Executing the Module
We executed the module, output of the __name__ variable is evaluated to __main__

Let use this important feature of detection of import vs execution to program our module words_name

Code in the file words_name.py is updated to read file as an argument and process the data in the file when the module is executed. Special variable __name__ is used to determine the execution and corresponding functions to process the data are called.
Code is not executed when the module is imported as the flow does not evaluate special __name__ to __main__

Paste the below code into words_name module or copy the code from GitHub

import sys

'''
    Module to read a text file and convert each word 
    first letter to CAPS.
    
    Execution of module takes a single argument that is 
    file to read and convert.
'''

def readfile(fileName):
    '''
       Reads input file passed as an agrument process the data
       and prints capitalized words to console.
       Args:
            Takes fileName as an argument
    '''
    try:
        fp = open(fileName, mode='rt', encoding='utf-8')
        words = fp.read().split()
        newWords = convertToCaps(words)
        print('Words in Capitalized form')
        for word in newWords:
            print (word)
        fp.close()
    except Excpetion as error:
        print(error)

def convertToCaps(wordsList):
    '''
       Reads input fila passed as an agrument process the data
       and prints capitalized words to console.
       Args:
            Takes wordsList as an argument
       Returns:
            returns wordsList with capitalized letter in each word
    '''
    capitalizedWords = []
    for word in wordsList:
        capitalizedWords.append(word.capitalize())
    return capitalizedWords

def main(inputfile):
    readfile(inputfile)

if(__name__ == '__main__'):
    if (len(sys.argv) < 2):
        print('Module takes file as input provide a file name:')
        exit (0)
    main(sys.argv[1])


Executed the module in the first instance without file, program is requesting to provide file name. In the second instance module is executed with file as input, data is processed and output to console.

Importing the module has no impact

Module words_name is imported and no request for file input or execution of module.

No comments:

Post a Comment

Operations on Python Dictionaries