Python Module & Third-Party Library

Crafting and Importing a Custom Python Module

Creating a Python Module:

  1. Initialize a New Python File:

    • Open your preferred text editor or integrated development environment (IDE).
    • Create a new file, for instance, mymodule.py.
    • Populate mymodule.py with a selection of functions or variables, such as:
    # mymodule.py
    
    def greet(name):
        return f"Hello, {name}!"
    
    def add(a, b):
        return a + b
    
    PI = 3.14159
    
  2. Save the File:

    • Save this file in the desired directory where you plan to store your module.

Importing and Utilizing the Module:

  1. Import the Module:

    • In a separate Python script or an interactive interpreter session, you can import the newly created module using the import statement.
    • Assuming your script file and module file reside in the same directory, create a new script file, such as main.py:
    # main.py
    
    import mymodule
    
    print(mymodule.greet("Alice"))
    print(mymodule.add(3, 4))
    print(mymodule.PI)
    
  2. Execute the Script:

    • Navigate to the directory containing both main.py and mymodule.py in your terminal or command prompt.
    • Run the script:
    python main.py
    
    • The expected output should be:
    Hello, Alice!
    7
    3.14159
    

Import Rules and Nuances:

  1. Module Search Path:

    • Python searches for modules in the following order when an import statement is encountered:

      1. Current Directory: The directory from which the script is being run.
      2. PYTHONPATH Variable: Directories listed in the PYTHONPATH environment variable.
      3. Standard Library Directories: Built-in Python libraries.
      4. Third-Party Library Directories: Libraries installed via pip.
    • You can inspect the current search path using sys.path:

    import sys
    print(sys.path)
    
  2. Absolute and Relative Imports:

    • Absolute Imports: Use the full path to the module, for example:
    import mymodule
    
    • Relative Imports: Use within packages to import sibling modules, for example:
    from . import mymodule  # Valid within a package context
    
  3. Module Reloading:

    • When modifying a module in an interactive interpreter, you might need to reload it using importlib.reload:
    import importlib
    import mymodule
    
    importlib.reload(mymodule)
    
  4. __name__ and __main__:

    • Each Python module has a built-in attribute __name__. When a module is executed directly, __name__ is set to '__main__'. This can be used to write test code within the module:
    if __name__ == "__main__":
        print(greet("World"))
        print(add(1, 2))
    
    • This ensures that the test code runs only when the module is executed directly, not when it is imported.

Summary:

  1. Create a .py file containing functions and variables.
  2. Use the import statement to include this module in other scripts.
  3. Understand the search path and rules for importing modules.
  4. Utilize importlib.reload to reload modules in an interactive environment.
  5. Use __name__ == "__main__" to include test code within the module.

By following these steps and principles, you can successfully create and utilize your own Python modules.

Understanding pip and Creating Your Own Third-Party Library

What is pip?

pip is the package management system for Python, widely utilized for installing and managing software packages. It significantly enhances Python’s capabilities by allowing programmers to easily add third-party libraries.

Installing Third-Party Libraries

You can install a third-party library using the following command:

pip install library_name

For instance, to install the requests library, you would use:

pip install requests

Viewing Installed Libraries

To view the libraries currently installed in your environment, execute:

pip list

Uninstalling Libraries

To remove a library, use the command:

pip uninstall library_name

For example, to uninstall the requests library:

pip uninstall requests

Creating Your Own Third-Party Library

Step 1: Prepare Your Code

Begin by structuring your code appropriately. For a simple library named my_package, the directory layout might look like this:

my_package/
    ├── my_package/
    │   ├── __init__.py
    │   ├── module1.py
    │   └── module2.py
    ├── tests/
    │   ├── __init__.py
    │   └── test_module1.py
    ├── setup.py
    ├── README.md
    └── LICENSE

Step 2: Write setup.py

The setup.py file is the heart of your package, containing metadata and configuration details. Here is an example:

from setuptools import setup, find_packages

setup(
    name="my_package",
    version="0.1",
    packages=find_packages(),
    install_requires=[
        # List dependencies here, e.g.:
        # 'requests',
    ],
    author="zhsh",
    author_email="zhsh@example.com",
    description="A simple example package",
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    url="https://github.com/zhsh/my_package",  # Project homepage
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

Step 3: Install Locally

To install your package locally, run:

pip install .

For development purposes, you might prefer an editable installation:

pip install -e .

Step 4: Upload to PyPI

To share your package with the world, you need to upload it to the Python Package Index (PyPI). First, ensure you have twine installed:

pip install twine

Next, build your package:

python setup.py sdist bdist_wheel

Finally, upload it using twine:

twine upload dist/*

You will need a PyPI account, and you will be prompted for your credentials during the upload process.

Using Your Library

Once your package is on PyPI, others can install it with:

pip install my_package

Summary

Leveraging pip for installing and managing third-party libraries significantly streamlines dependency management in Python projects. Creating and publishing your own third-party library is a straightforward process, enabling your code to be utilized and contributed to by developers worldwide.