Python Project - Packages and Modules

Goal

Get familiar with the fundamental terms of a Python project.

Project, Packages, Modules, And Scripts

  • Project: A directory, also known as the top-level package, which contains packages and modules
  • Package (in a project): a directory which contains modules and/or packages (sub-directories)
  • Module: a Python script (.py) which can be imported with import and from
  • Script: a Python script (.py) which can be exected from the terminal. This will be the only reference to the word script, since we're not scripting, we're developing a Python package

Packages Which Are Not Part Of The Project

  • Package (built-in): A package that is shipped with Python and can be imported with import and from. For example, os, pathlib, etc.
  • Package (pip): A package that was installed by pip and can be either imported with import and from, or get executed from the command-line (terminal). Think about it, pip stands for Package Installer for Python. For example numpy, pillow, etc.

Importing Project Modules

  • Python project's packages and modules can be (and should be) imported with relative paths from any module which is part of the same project. An example is available in src/appy/core/app.py

    from ..utils import message, img_ascii
  • If you intend to import a package or a module that is not part of the same project, you'll have to use absolute paths. This can be done with importlib, see this StackOverflow Question.

Why do relative imports raise a problem in pylint?

I don't know, all I can say is that it doesn't happen with flake8, I'm referring to the following warning

Attempted relative import beyond top-level-package pylint(relative-beyond-top-level)

This blog post is part of the Python Project series, and is based on this GitHub repository - unfor19/python-project.

The GitHub repo includes an example of a Python project, and Wiki Pages that describe the necessary steps for developing, creating and distributing a Python package.


Originally published at github.com/unfor19/python-project on October 30, 2020

Recommended Posts

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *