14. Python Development

14.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

14.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

14.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.

14.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

14.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

14.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

14.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 Relative Imports <https://realpython .com/absolute-vs-relative-python-imports/>`_

14.6. List Comprehensions

Syntax:

[expression for target1 in iterable1 if condition1
            *for target2 in iterable2 if condition2 ...
            *for targetN in iterableN if conditionN ...]