Python Feature Image

What are modules in PythonModules refer to a file containing Python statements and definitions. Module is a file containing Python code, for example: example.py ,and its module name would be example . We use modules to break down large programs into small manageable and organized files. We load module only once regardless of number of times we import it. This prevents the module execution from happening over and over again if multiple imports occur.

List Available Modules

To list all modules, type pydoc modules in terminal.

or in Python code:

print (help('modules') )

# python 3

# prints a list of existing modules
print( help('modules'))
List

Note: in Ubuntu Linux, as of 2013-11-25, there’s a bug that both pydoc modules and help('modules') will crash Python. Use python3 instead.

sudo apt-get install python3

pydoc3 module

Reading Module Documentation

To read the doc of a module, in terminal, type pydoc module_name, or in Python program call help(module_name).

# python 3

import os

# print the module's online manual
print(help(os))

Note: the documentation from pydoc is not identical to the official documentation. Doc from pydoc is generated from the module source code, and is terse and technical.

List Module’s Function/Variable Names

  • dir(module_name) → list all names exported by the module module_name.
  • dir() → list all names in current scope (but not standard functions). To list standard functions, import __builtin__ first, then dir(__builtin__).
# python 3

import re

# print all names exported by the module
print(dir(re))

# output

# ['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'Match', 'Pattern', 'RegexFlag', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_cache', '_compile', '_compile_repl', '_expand', '_locale', '_pickle', '_special_chars_map', '_subx', 'compile', 'copyreg', 'enum', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'functools', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'template']

Using Module

import module_name → load a module.

module_name.function_name → call a function in module.

# python 3

# import the standard module named os

import os

# example of using a function
# get current dir
print(os.getcwd())

# /Users/xah/web/xahlee_info/python

Import Function Names from Module

We can directly import Module’s function name by the syntax:

  • from module_name import name_1, name_2, … → import several functions.
  • from module_name import * → import all functions.
# python 3

from os import getcwd

# current dir
print(getcwd())

Default “module”

All global (variable/function) names in Python are considered to be in the pseudo-module namespace named __main__.

# python 3

print(dir())
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

print(dir("__main__"))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Module Search Paths

Python module search paths is stored in the variable sys.path.

# python 3

import sys
import pprint

# pretty print module search paths
pprint.pprint(sys.path)

# ['/Users/xah/web/xahlee_info/python',
#  '/Users/xah/anaconda3/lib/python37.zip',
#  '/Users/xah/anaconda3/lib/python3.7',
#  '/Users/xah/anaconda3/lib/python3.7/lib-dynload',
#  '/Users/xah/anaconda3/lib/python3.7/site-packages',
#  '/Users/xah/anaconda3/lib/python3.7/site-packages/aeosa']

List Loaded Modules

Loaded module names is stored in the variable sys.modules.

# python 3

import sys
import pprint

# pretty print loaded modules
pprint.pprint(sys.modules)

# sample output
# {'__main__': <module '__main__' from '/Users/xah/web/xahlee_info/python/xxtemp.20190318.38b.py3'>,
#  '_abc': <module '_abc' (built-in)>,
#  '_bootlocale': <module '_bootlocale' from '/Users/xah/anaconda3/lib/python3.7/_bootlocale.py'>,
#  '_codecs': <module '_codecs' (built-in)>,
# ...
#  'zipimport': <module 'zipimport' (built-in)>}

Note: The exact contents of sys.path are installation-dependent. The above code block will almost certainly look slightly different on your computer. The operating system used in this lesson is macOS. If you would like to see what the path structure looks like in a Windows environment, check out the original article that this course is based on.

Read More Python Blogs here.

Leave a Reply