Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Python Module

Introduction

Modules are a simple way to organize a program which contains program code, variables etc.. All these definitions and statements are contained in a single Python file. The name of the module is the name of the file name with .py extension. Modules are not loaded unless we execute in Python interpreter or call within a program. In Python, there are modules in a standard library, current directory or directories containing .py files (in fact each file with .py extension is a module). To define a module, you can use Python IDLE, Notepad++ or any suitable text editor. Lets create a file called factorial.py which will create the factorial (in mathematics, the factorial of n [a positive integer] is the product of all positive integers less than or equal to n.) of a positive integer as well as some other jobs in the current directory.

Example:

# factorial.py
def factcal(n): # Create the factorial of a positive integer    
    fact = 1
    while n>0:
          fact *= n
          n=n-1
          if(n<=1):
            break
    else: # Display the message if n is not a positive integer.        
          print('Input a correct number....') 
          return
    return fact

def factdata(n): # return the numbers of factorial x
    result = []
    while n>0:
       result.append(n)
       n = n - 1
       if(n==0):
        break
    else: # Display the message if n is not a positive integer.        
       print('Input a correct number....') 
       return
    return result

Importing a module:

In order to use a module, use import statement. Go to the Python interpreter and execute the following command :

python import module

 

There are two functions factcal(n) and factdata(n) are defined in factorial.py. Using the module name we can access the functions. functions factcal(5) creates the factorial of 5 and factdata(5) shows the numbers involved in factorial 5.

python module functions

 

In the above example instead of factorial.factcal(n) or factorial.factdata(n) we can assign it to a local name. See the following codes, we assign factorial.factcal into fumber and factorial.factdata into fdata.

python module local assign

 

In Python, a module name (as a string) is stored within a module which is available as the value of the global variable __name__.

python module name

 

from..import statement

from .. import statement is used to import selective names(s) or all names that a module defines. See the following codes.

python from import

 

In above example when we execute factdata(9), an error arise as we only import factcal. To avoid this type of situation import all name(s) with import command adding with a * symbol.

Executing modules as scripts:

To run a Python module as a script use the following syntax.

python filename <arguments>

The program code in the module will be executed with the __name__ set to "__main__" which means adding some additional code at the end of the module. See the source code of script-factorial.py.

# script-factorial.py
def factcal(n):
# Create the factorial of a positive integer    
    fact = 1
    while n>0:
          fact *= n
          n=n-1
          if(n<=1):
            break
    else:
# Display the message if n is not a positive integer.        
          print('Input a correct number....') 
          return
    print(fact)
def factdata(n): # return the numbers of factorial x
    result = []
    while n>0:
       result.append(n)
       n = n - 1
       if(n==0):
        break
    else:
# Display the message if n is not a positive integer.        
       print('Input a correct number....') 
       return
    print(result)

if __name__ == "__main__":
    import sys
    factcal(int(sys.argv[1]))
    factdata(int(sys.argv[2]))

Now execute the file at the command prompt (here in windows).

python script executes in windows command line

 

Modules Path:

  • In the directory ,the script is saved or in the current directory.
  • in PYTHONPATH (a list of directory names), default search path for module files. PYTHONPATH is an environment variable. You will get it using 'env' command in UNIX-based operating system or in the properties of My Computer in windows system.
  • the installation-dependent default.

Standard Module:

Python comes with numerous modules.

Python has many standard modules as a library. These are aimed to add efficiency or to access operating system primitives. Some of the modules depend upon the operating system.

sys is a Python Standard module which is very useful. It is built into every Python interpreter.

The dir() function:

The built-in function dir() is used to get the names (a sorted list of strings), a module is defined. Check it into Python shell.

python dir function

 

Previous: Python User define function
Next: Home - Python Calendar Module

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Find current directory and file's directory:

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")

Ref: https://bit.ly/3fy0R6m