Python Programming

·

2 min read

One script

  1. Create a python script file (.py)
  2. Write statements and save
  3. Run command: python <path to file>
  4. Or start the file with #! /usr/bin/python then give execute permission chmod +x <file> and run the file only.

Project

Project structure

  1. Create a working directory with structure
    myproject/
    │
    ├── src/
    │   └── myprogram/
    │       ├── __init__.py
    │       ├── __main__.py
    │       ├── config.toml
    │       ├── module1.py
    │       └── module2.py
    │
    ├── tests/
    │   ├── test_module1.py
    │   └── test_module2.py
    │
    ├── LICENSE
    ├── MANIFEST.in
    ├── README.md
    └── pyproject.toml
    
  2. The __main__.py will be the entry point of the program and has code pattern: ```python from myprogram import module1, module2 def main(): """program function description"""

if name == "main": main()

3. The `__init__.py` to represents the root of the package. It will have package constants, configuration handler. Variables defined in `__init__.py` become available as variables in the package namespace. Best practice for this file:
```python
from importlib import resources
try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib

__version__ = "1.0.0"

_cfg = tomllib.loads(resources.read_text("reader", "config.toml"))
URL = _cfg["feed"]["url"]
  1. The module1.py and module2.py provides functions, object types that is used by __main__.py. Import the package itself can help the module access the package constants and variables. Example a module file: ```python import myprogram

def function1(): '''describe the feature of function1''' ... def function2(): '''describe the feature of function2''' ... ```

  1. The pyproject.toml contains metadata of the package, it describes:
    1. Which build-system: a tool responsible for creating the actual files that you’ll upload to PyPI.
    2. Dependencies
    3. Project information

Using project localy

Build package

  1. Install two tools build and twine: python -m pip install build twine
  2. Build the package: in the project root folder, run python -m build
  3. Result: a dist folder created with two package formats created in .tar.gz and .whl in
  4. Confirm the package build:
    • unzip the .tar.gz and inspect contents with tree.
    • or run twine check dist/

      Upload to the [[PyPI - Python Package Index]]

  5. Create an account on pypi.org
  6. Run command twine upload -r testpypi dist/*
  7. Twine will ask you for your username and password.

Reference: realpython.com/pypi-publish-python-package