Python - Modules

What is a Module?

A file containing set of python statements and definitions.

Why to use Python Modules?

  • It is used to organize the python code logically.
  • Grouping related code into a module makes the code easier to understand and use.
  • It provides reusability of code.
  • Modifying or updating the code is easier. Hence less maintanence cost.

  • How to Create a Module in Jupyter notebook ?

    1. Create the Python 3 note book and save the file as userdefinedfunction (File extension will be .ipynb)

    2. Code all the required functions. In this example Welcomeuser function

    # Function to Welcome User
    def welcomeUser(name):
    """ 
    This function welcome's the user for python class
    """
    print("Dear "+ str(name) +", Welcome to Python Tutorials") 
    

    3. Download the file [ File -> Download as -> Python(.py) ]



    4. Move the downloaded file to the mentioned path. "C:\ProgramData\Anaconda3\Lib"\



    Note : ProgramData folder will be hidden folder. Change the setting as per below image to view the hidden folder and now navigate to the mentioned path ("C:\ProgramData\Anaconda3\Lib"\)

    Naming convention for a Module

  • Modules should have short, all-lowercase names.
  • Underscores can be used in the module name if it improves readability

  • How to import a Module?

    Syntax : 
    import module1[, module2[,... moduleN]
    #Sample Program 
    # Use the "import" keyword to import the module.
    import userdefinedfunction
    
    # "Module Name.Function Name" to access the function
    userdefinedfunction.welcomeUser("Vinoth")
    
    Output:
    Dear Vinoth, Welcome to Python Tutorials
    

    Import with Renaming

    Alias name can be created while importing a module by using the "as" keyword
    Advantage : No need to mention the full module name through out the program. It can be mentioned with alias name.

    # udf is the alias name of the module
    import userdefinedfunction as udf
    udf.welcomeUser("Anand")
    udf.welcomeUser("Pranav")
    
    Output:
    Dear Anand, Welcome to Python Tutorials
    Dear Pranav, Welcome to Python Tutorials
    

    Built-in Modules

    1. datetime module

    # Entire datetime module will be imported
    import datetime
    datetime.datetime.now()
    
    Output:
    datetime.datetime(2019, 9, 21, 9, 55, 11, 835018)
    

    2. math module

    # Entire math module will be imported
    import math
    print("The value of pi is", math.pi)
    print("Factorial of 5 is",format(math.factorial(5)))
    
    Output:
    The value of pi is 3.141592653589793
    Factorial of 5 is 120
    

    Reference Link

    Python standard modules list

    https://docs.python.org/3/py-modindex.html

    Using from...import statement

    Specific names(functions) can be imported from a module without importing the whole module.
    Advantage: Better performance

    # import only pi from math module
    from math import pi
    print("The value of pi is", pi)
    
    Output:
    The value of pi is 3.141592653589793
    

    Using from...import * Statement

    It is also possible to import all names from a module into the current python file.

    # import all the names from math module
    from math import *
    print("The value of pi is", pi)
    
    Output:
    The value of pi is 3.141592653589793
    

    Note: Importing everything with the asterisk (*) symbol is not a good programming practice. This can lead to duplicate definitions for an identifier. It also hampers the readability of the code.

    Using the dir() built in function

    dir() function list all the function names (or variable names) in a module.

    # Import built-in module datetime
    import datetime
    dir(datetime)
    
    Output:
    ['MAXYEAR',
     'MINYEAR',
     '__builtins__',
     '__cached__',
     '__doc__',
     '__file__',
     '__loader__',
     '__name__',
     '__package__',
     '__spec__',
     'date',
     'datetime',
     'datetime_CAPI',
     'sys',
     'time',
     'timedelta',
     'timezone',
     'tzinfo']
    

    Using __ doc __

    By using double under score (__) doc (__), the function description can be retrived.

    import userdefinedfunction as udf
    udf.welcomeUser.__doc__
    
    Output:
    " \n    This function welcome's the user for python class\n    "
    

    The reload() Function

    When the module is imported into a script, the code in the top-level portion of a module is executed only once.
    Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again

    # Sample code to reload the function after updation
    import userdefinedfunction as udf
    import importlib
    importlib.reload(userdefinedfunction)
    
    udf.welcomeUser("Vinoth")
    
    Output:
    Dear Vinoth, Welcome to Python Tutorials
    Added the new function
    
    Total Website Visits: 40445
    © Copyright 2018 - 2020. All Rights Reserved.

    Developed by Vinoth Rathinam