What Is Module

This section provides a quick introduction of module, which is an object of the 'module' data type that can store attributes, functions, classes and sub-modules.

What Is a Module? A module is an object of the "module" data type that can store attributes, functions, class classes.

Here are the guidelines you should remember on using modules.

1. There is no Python statement that defines a module.

2. A module is defined in an external file.

3. A module is imported into memory using the "import" statement, using these syntax:

import module_name
import module_name as variable_name

When an "import module_name" statement is executed, Python system will do the following:

Here is an example of a module file, module_test.py:

#  module_test.py
#- Copyright 2011 (c) HerongYang.com. All Rights Reserved.
#
print("Hi there! - from 'module_test' module")

version = "1.00 - from 'version' attribute"

def help():
   print("How can I help you? - from 'help()' function")

class first:
   print("Welcome on board! - from 'first' class")
   count = 0
   def rise(self):
      first.count += 1
      print(f"count = {first.count} - from 'rise()' method")

You can save module_test.py in the current directory and run the following code in Python shell to test it.

herong$ ls -l
-rw-r--r--@ 1 herong  staff  423 Apr 1 07:35 module_test.py

herong$ python

# import the module
>>> import module_test
Hi there! - from 'module_test' module
Welcome on board! - from 'first' class

# check the module object
>>> m = module_test
>>> type(m)
<class 'module'>
>>> id(m)
4309263360

# check module attribute 'version' and function 'help()'
>>> m.version
"1.00 - from 'version' attribute"
>>> m.help()
How can I help you? - from 'help()' function

# create an instance from the module class 'first'
>>> f = m.first()
>>> f.rise()
count = 1 - from 'rise()' method
>>> f.rise()
count = 2 - from 'rise()' method

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

 Iterators and Generators

 List, Set and Dictionary Comprehensions

 Classes and Instances

Modules and Module Files

What Is Module

 "import module" - Two-Step Process

 sys.modules - Listing Loaded Modules

 importlib.reload(module) - Reloading Module

 What Are Module Members

 "from module import member" Statement

 "from module import *" Statement

 What Is __all__ List

 __pycache__/module.version.pyc Files

 What Is the __main__ Module

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB