Python
Installation
CentOS, Rocky Linux
yum install -y python3 (?)
Fedora
dnf install -y python3
FreeBSD
pkg install -y python3
Windows
Go to download
Set it to the PATH.
Usage, tips and tricks
Virtual environments
Virtual environment is separated “sandbox” (isolated location) where is collected set of software (components, modules, libraries) with their versions together as software state. On single machine (developer machine, production machines, etc.) can be prepared many separated and different sets/states of software. Perhaps module or project specific sets. One of these sets contains even Python with specific version.
Python internal module venv can be used as virtual environment tools. Also, conda can be used for virtual environment handling.
Windows
With python launcher
py --version
Get installed python versions:
py -0
Get python launcher help
py --help
*nixes
python --version
# or
python3 --version
Python packages
Python packages web page: PyPI
When pip is not installed:
Windows
py -m ensurepip --default-pip
py -m pip --version
# Or
py -3 -m pip --version
*nixes
python3 -m ensurepip --default-pip
pip --version
Installing packages
python -m pip install SomePackage
python -m pip install SomePackage==1.0.4 # with specific version
python -m pip install "SomePackage>=1.0.4" # with minimum version
python -m pip install --upgrade SomePackage # upgrade existing already installed software
Freezing
Get state of software and their versions.
To get installed packages (inside venv) into requirements.txt
pip freeze > requirements.txt
To install frozen (requirements.txt) packages
pip install -r requirements.txt
Guide to make your own Python packages: Python Packaging User Guide
Execute project application
conda activate %PROJECT_NAME% # or venv
python -m module.name
conda deactivate
conda activate ${PROJECT_NAME} # or venv
python -m module.name
conda deactivate
Execute project tests
Execute tests:
python -m unittest discover -s ./ -p *_test.py
Exit REPL
Ctr+Z and then Enter
Code examples
Lambda
maximum_number = lambda x, y: x if x > y else y
print("Max:", maximum_number(8, 5))
Map
number_list = [4, 3, 2, 1]
print(list(map(lambda x: x ** 2, number_list)))
Iteration I
for item in number_list:
print("Item=", item)
Iteration II
for index in range(len(number_list)):
print("number_list[", index, "]=", number_list[index])
Iteration III
for index, item in enumerate(number_list):
print("Item=", item, ",", index)
Chained map and filter chain
print(
list(
filter(
lambda persona: persona.id > 2,
list(
map(
lambda id: Person(id, None),
number_list
)
)
)
)
)
Switch I
val = "abc"
switcher = {
"abc": lambda: int(1),
"def": lambda: int(2)
}
print("Switch: abc=", switcher[val]())
Switch II
val = "def"
switcher = {
"abc": int(1),
"def": int(2)
}
print("Switch: def=", switcher[val])
val = "xyz"
print("Switch: def=", switcher.get(val, None))
Switch III (starting from Pyton 3.10)
A
def number_to_string(val: int):
match val:
case 0:
return "zero"
case 1:
return "one"
case 2:
return "two"
case _:
return "something"
case _: can be case default?
B
That’s not working!
ABC = "abc"
def number_to_string(val: str):
match val:
case ABC:
print("zero")
case "def":
print("one")
case "ghi":
print("two")
case _:
print("Unknown")
Possible solution for that.
import types
constants = types.SimpleNamespace()
constants.ABC = "abc"
constants.DEF = "def"
constants.GHI = "ghi"
val: str = "abc"
match val:
case constants.ABC:
print("zero")
case constants.DEF:
print("one")
case constants.GHI:
print("two")
case _:
print("Unknown")
Functional (map, filter, reduce)
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
filtered = list(filter(lambda x: x % 2 == 0, numbers))
result = reduce(lambda x, y: x + y, numbers)
List comprehensions
squared = [x**2 for x in numbers if x % 2 == 0]
Itertools
import itertools
numbers = [1, 2, 3, 4, 5]
squared = itertools.starmap(lambda x, y: x**y, zip(numbers, itertools.repeat(2)))
Testing mocking
cucumber behave
pip install behave
./features/steps/tutorial.py
from behave import *
@given('we have behave installed')
def step_impl(context):
pass
@when('we implement a test')
def step_impl(context):
assert True is not False
@then('behave will test it for us!')
def step_impl(context):
assert context.failed is False
./features/tutorial.feature
Feature: showing off behave
Scenario: run a simple test
Given we have behave installed
When we implement a test
Then behave will test it for us!
To execute tests
behave
Python Enhancement Proposals (PEPs)
Frameworks
Django
Flask (http://flask.pocoo.org/)
Falcon
Jinja2 (Template engine : http://jinja.pocoo.org/)
Chameleon (Template engine : https://chameleon.readthedocs.io/en/latest/)
Package management
wget -c https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
--user
Under **~/.local/bin**
--proxy='${$http_proxy}'
pip --version
Eclipse
http://www.pydev.org/updates
Project setup
Activate (updated [pip, etc.]) env and:
touch main.py .gitignore README.md requirements.txt
pip completion --bash >> ~/.profile
pip install Flask
pip freeze > requirements.txt
create main
nano main.py
with content
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
Unit test and run Flask main
python -m unittest discover
# By pattern test. Default is test*.py
python -m unittest discover -s ./ -p *Test.py
export FLASK_ENV=development
python main.py
git add **.py .gitignore README.md requirements.txt
Deactivate env.
PYTHONPATH is for searching modules, like PATH for commands.
Build python
# TO build python
sudo dnf install -y openssl-devel sqlite sqlite-devel
PYTHON_MAJOR=3
PYTHON_MINOR=12
PYTHON_PATCH=5
PYTHON_VERSION=${PYTHON_MAJOR}.${PYTHON_MINOR}.${PYTHON_PATCH}
TEMP_DIR=~/temp/python
PYTHON_BUILD_DIR=Python-${PYTHON_VERSION}
PYTHON_TEMP_BUILD_DIR=${TEMP_DIR}/${PYTHON_BUILD_DIR}
PYTHON_TEST_BUILD_DIR=${TEMP_DIR}/test
mkdir -p ${TEMP_DIR}
cd ${TEMP_DIR}
wget -c https://www.python.org/ftp/python/${PYTHON_VERSION}/${PYTHON_BUILD_DIR}.tgz
tar xvzf ${PYTHON_BUILD_DIR}.tgz
cd ${PYTHON_BUILD_DIR}
./configure --prefix=/opt/python-${PYTHON_VERSION} --exec-prefix=/opt/python-${PYTHON_VERSION}
make
sudo make install
mkdir -p ${PYTHON_TEST_BUILD_DIR}
cd ${PYTHON_TEST_BUILD_DIR}
/opt/python-${PYTHON_VERSION}/bin/python3.12 -m venv ./.venv
source ./.venv/bin/activate
pip --version
exit
PyCharm
“File” -> “Settings” -> Python Integrated Tools -> Default test runner: Unittest
Running tests have a problem: working directory has to be set for tests.
See also
PEP 8 – Style Guide for Python Code