Dong Nguyen
Python

Container with distroless

FROM python:3-slim AS build-env
COPY . /app
WORKDIR /app

# may need to run install
RUN pip install

FROM gcr.io/distroless/python3
COPY --from=build-env /app /app
WORKDIR /app
CMD ["server.py", "/etc"]

Dict union

dict1 = {"a": 1, "b": 2, "same" : "old"}  
dict2 = {"c": 3, "d": 4, "same": "new"}  

# before 3.9
dict3 = {**dict1, **dict2}

# >=3.9
dict3 = dict1| dict2

print(dict3)
#return {"a": 1, "b": 2, "c": 3, "d": 4, "same": "new"}

Random string with built-in functions

import os
serial = int.from_bytes(os.urandom(20), byteorder="big")

import secrets
token = secrets.token_hex(16)

Break a list into chunks of size N in Python

def divide_chunks(entries, page_size):
    for i in range(0, len(entries), page_size):
        yield entries[i:i + page_size]

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

x = divide_chunks(my_list, 4)
for section in x:
    print(section)

Count repeated word from string:

s = "hello this is hello this is baby baby baby baby hello"

# 1
from collections import Counter
import re
reg = re.compile('\\S{4,}')
c = Counter(ma.group() for ma in reg.finditer(s))

# 2
from collections import defaultdict
c = defaultdict(int)

for w in s.split():
    if len(w)>=4:
        c[w] += 1

# 3
from collections import Counter

c = Counter(w for w in s.split() if len(w) >= 4)

Generator as stream

import time

def my_generator():
    total = 0
    while True:
        time.sleep(1)
        total += 1
        err = 0
        if total == 5:
            err = 1
        if total == 10:
            err = 2
        yield total, err

result = my_generator()

for time_spent, error in result:
    print ("Time spent is:", time_spent, 'error: ', error)
    if error == 2:
        break

Delay function:

import time
    
def main():
    
    while True:
        print("DateTime " + time.strftime("%c"))
        time.sleep(1) # delays for 1 seconds

if __name__ == '__main__':
    main()

Merge two dictionaries

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}

Python's namedtuples can be a great alternative to defining a class manually

# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')

# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)

# Like tuples, namedtuples are immutable:
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"

"is" vs "=="

# "is" vs "=="

>>> a = [1, 2, 3]
>>> b = a

>>> a is b
True
>>> a == b
True

>>> c = list(a)

>>> a == c
True
>>> a is c
False

# • "is" expressions evaluate to True if two 
#   variables point to the same object

# • "==" evaluates to True if the objects 
#   referred to by the variables are equal

Python's shorthand for in-place value swapping

# Why Python Is Great:
# In-place value swapping

# Let's say we want to swap
# the values of a and b...
a = 23
b = 42

# The "classic" way to do it
# with a temporary variable:
tmp = a
a = b
b = tmp

# Python also lets us
# use this short-hand:
a, b = b, a

Dicts can be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None

def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()

>>> dispatch_if('mul', 2, 8)
16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None

Publish Pipy

python3 -m pip install --user --upgrade setuptools wheel twine
python3 setup.py sdist bdist_wheel

python3 -m twine upload dist/*

# release pipitest:
python setup.py register -r pypitest

# add download link
python setup.py sdist upload -r pypitest

# release to live:
python setup.py sdist upload -r pypi