10. Python Development

10.1. Set Up Venv

In project file or where you wish to start

# if your default python is not preferred point to the
# python directory where your preferred python exists
$ python -m venv ./venv
# where ./venv is the name of the new directory in current directory
$ source venv/bin/activate  #start venv
$ deactivate    #ends venv

10.2. Requirements.txt

Allows for all requirements packages (dependencies) to be loaded at one command. Requirements text commands-

export requirements.txt
pip freeze > requirements.txt   # writes the requirements.txt file with dependencies, one on each line
cat requirements.txt    # shows what's in requirements.txt
import requirements.txt
pip install -r requirements.txt   # installs all the dependencies listed in the requirements.txt file

10.3. isort

Automatically sort imports by type and alphabetically

pip install isort
vim <file_name>.py
isort <file_name>.py

Requires Python 3.6 to run.

10.4. Lists vs Dictionaries vs Tuples

L[] vs D{} vs T() maps to array vs records vs immutable collection of objects
L[] accessed by offset, D{} accessed by key, T() accessed by offset

10.5. Python Imports

Python module is a .py file and Python package is a directory/folder contains modules. In < Python 3.3 a package is a folder that contains an __init__.py file in it. This is a convenience since in Python packages and modules need not originate in the file system.

Given the following directory:

└── project
    ├── package1
    │   ├── module1.py
    │   └── module2.py
    └── package2
        ├── __init__.py
        ├── module3.py
        ├── module4.py
        └── subpackage1
            └── module5.py

See how python modules, classes and fuctions are imported with aboslute imports and relative imports from the driectory above with the guidlines below

10.5.1. Absolute Imports

from package1 import module1
from package1.module2 import function1
from package2 import class1
from package2.subpackage1.module5 import funtion2

Relative imports are to be preferred

10.5.2. Relative Imports

Import from same directory use 1 dot ., import from parent directory use 2 dots .., import from grandparent directory use 3 dots …, and so on.

To import a class from the current directory use:

from . import class

Where the single dot is the current directory.

Thanks to Real Python- Absolute vs Re;ative Imports <https://realpython.com/absolute-vs-relative-python-imports/>`_