MODULES IN PYTHON

 


Module technically is a file containing a set of functions that can be included in a Python application. In practice, modules are implemented as one of the ways to organize and reuse codes efficiently.

The previous posts contain Trinket embedded editor which includes some of the basic modules such as:

  • builtins
    • any - Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
    • filter - Return those items of sequence for which function(item) is true.  If function is None, return the items that are true.  If sequence is a tuple, or string, return the same type, else return a list.
    • input - Equivalent to eval(raw_input(prompt)).
    • len - Return the number of items of a sequence or mapping.
    • map Return a list of the results of applying the function to the items of the argument sequence(s).  If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length.  If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).
    • open Open a file using the file() type, returns a file object.  This is the preferred way to open a file.
    • range - Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3].  The end point is omitted! These are exactly the valid indices for a list of 4 elements.
    • reduce - Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
    • sort - sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
    • sum - Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0).  When the sequence is empty, return start.
    • zip - Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences.  The returned list is truncate in length to the length of the shortest argument sequence.

Creating custom module is also possible.

For example, the following is a module emoticonize.py that reads data from emoticon.txt and provides a function addEnding() which appends an emoticon to a message.

# emoticonize.py
# emoticon data from https://pc.net/emoticons/

with open("emoticon.txt", 'r') as f:
  #using list comprehension to read rows
  listEmoticon = [row.rstrip('\n').split(' ') for row in f]

def addEnding(text):
  listToken=text.lower().split()
  #print(listToken)
  emoticon=''
  for token in listToken:
    #print (token)
    #using list comprehension to find matching icon for the token
    listMatchingEmoticon=[item for item in listEmoticon if item[1].lower()==token]
    if (len(listMatchingEmoticon)>0):
      emoticon+= listMatchingEmoticon[0][0]
  text += ' '+emoticon
  return text


Another python script file would be able to use this function by importing the module and then call the function name. In the following example, main.py implements the function call via lambda and list comprehension statements (however lambda statement is commented).

# main.py
import emoticonize

print("\n====================\n")
print("1. Convert message to list")
textMessage='''i am happy
so sad to hear about this
this is super shocked
wow surprised
i'm confused
frustrated day
that is sarcastic
getting married soon
just joking'''
#convert string to list
listMessage=textMessage.split('\n')

print("\n====================\n")
print("2. Display original message:\n") 
print("\n".join(listMessage)) 

print("\n====================\n")
print("3. Display emoticonized message:\n")
#lambda style
#listEmoticonizedMessage= map(lambda message:emoticonize.addEnding(message), listMessage)

#list comprehension style (for a better code clarity)
listEmoticonizedMessage=[emoticonize.addEnding(message) for message in listMessage]
print("\n".join(listEmoticonizedMessage)) 

print("\n====================\n")


In the next posts, two commonly used modules in data science will be discussed i.e. numpy and matplotlib.

Post a Comment

0 Comments