Skip to content

Modules & Packages

Modules

  • To link all of the files together, use Modules for organinzing files
  • Each .py file is a module.
  • Import modules using the import keyword:
import file_name
print(file_name)

pycache

  • When importing, Python generates a pycache folder containing compiled versions of modules for faster execution
  • pycache is created every time we run a file with, import statements
  • instead of loading up utility py, it's going to load up compiled version of utility

Packages

  • A package is a folder containing multiple modules.

  • Import syntax:

import package_name.module_name
from package_name.subpackage_name import func_name

In PyCharm, creating a package automatically adds an init.py file. Packages can be nested inside other packages. - You can create a new package inside a package, refactor the file inside a package of package to move a file - To import a package of package file import package_name.package_name.module_name

or

syntax: from package_name.subpackage_name import func_name print(func(argument))

from package_name import func_name1, func_name2 from package_name import * [(*) stands for all]

Files being executed as scripts rather than imported — Python sets

  • The IDE allows us to actually select and do view quick documentation by select the text > view > quick documentation

The name == "main" Idiom

  • When a file is run directly, Python sets name == "main".
  • When you want a file to act only as a module, make sure it is imported (not run)

  • The name main is given specifically to the file that we run.

  • This is used when you only want to run the main file
if __name__ == '__main__':
    do something()

You see these lines, when we want to make sure that we run a module only if this is the main module.
Maybe we have code that we don't want to run unless it's the main file.

External Packages & Pip

(GitHub is a social network for programmers. People can view your code and download it. To know how popular a package is known by stars(like) or forks(copy))

pip is python package installer

In pycharm

  • Go to settings > python interpreter > + sign > search package > install package
  • To import installed package use import statement

Through terminal

Install a package pip install package name

To see all installed packages pip list

Uninstall package pip uninstall package_name

Upgrading package pip install --upgrade package_name

Check pip version pip -V

Through version pip install package_name==version_number

PYTHON BUILT-IN MODULES

  • Python comes with a rich standard library.
  • These modules actually were installed when we downloaded the Python interpreter.
from array import array
from collections import Counter, defaultdict, OrderedDict

import datetime
import sys
import random

help(random)           #shows what it does
print(dir(random))     #lists out all the methods

Good practice is to import only what you need.

from random import shuffle,...,etc

Changes the name of random to something else, can call it when writing the code.

import random as AnyName

Example:

Random Module

print(random.random())                  # float between 0 and 1
print(random.randint(1, 10))            # integers from the criteria
print(random.choice([1, 2, 3, 4, 5]))   # random element from the iterator list
myList = [1, 2, 3, 4, 5]
random.shuffle(myList)          # shuffles the variable given
print(myList)
import random
# Useful Tip: You can also change the name when you import it, like:
# import random as AnyName
# Or import only what you need: from random import shuffle

# This gives you information and documentation about how to use the module:
# help(random)

print(random.random())        # Gives you a random decimal number between 0 and 1
print(random.randint(1, 10))   # Gives you a random whole number between 1 and 10
print(random.choice([1,2,3,4,5])) # Picks one random item out of this list

# Shuffling a list
myList = [1, 2, 3, 4, 5]
random.shuffle(myList)        # Mixes up the items in your list randomly
print(myList)

# If you want to read what a function does quickly inside your IDE (like PyCharm or VS Code), 
# Highlight the word with your mouse and go to View > Quick Documentation.

Sys Module

It communicates with the terminal as we give the arguments

sys.argv

first = sys.argv[1]
second = sys.argv[2]

print(f'hello, {first} {second} ')

IN TERMINAL python3 file.py marwa abubaker (args) hello, marwa abubaker (output)

Useful Modules in Python

Python provides different kinds of modules and data types that are commonly used:

  • Built-in Data Types
    Examples: int, str, list, dict, etc.
    These are available by default in Python.

  • Custom Data Types
    Created using classes in Object-Oriented Programming (OOP).
    Example: defining your own Car or Employee class.

  • Specialized Data Types (collections module)

  • Counter → counts occurrences of elements.
  • defaultdict → provides default values for missing keys.
  • OrderedDict → remembers the order of insertion.

PYTHON MODULES(Commomly used)

Collections Module

from collections import Counter

li = [1, 2, 3, 4, 5, 6, 7, 7]
print(Counter(li))        # counts the occurence
# creates a counter object that is a subclass of dict
sentence = 'hello hello hi hi hi'
print(Counter(sentence))  # counts the occurence of each character

defaultdict If key not found returns default value, the first parameter should be function or data type like int.

from collections import defaultdict, OrderedDict

dd = defaultdict(lambda: 5, {'a': 1, 'b': 2})
print(dd['c'])     # prints 5 instead of key error

d = OrderedDict()  # keeps the order of insertion
d['a'] = 1
d['b'] = 2

d1 = OrderedDict()
d1['b'] = 2
d1['a'] = 1
print(d == d1)     # false because order matters in orderedDict

OrderedDict - if we use normal dict it would be true because order doesn't matter in normal dictionary. - OrderedDict is useful when you want to make sure the order of insertion matters.

Datetime Module

import datetime

print(datetime.time(5, 45, 2))  # time(hour, minute, second, microsecond)
print(datetime.date.today())    # current date

Array Module

  • They are useful when we want to store large amount of data, uses less memory space.
arr = array('i', [1, 2, 3, 4, 5])  # array(typecode, initializer)
print(arr)                         # can be accessed like a list
print(arr.typecode)                # prints the typecode of the array