Awesome Python

A reference of Python language features, collections, and standard library essentials.


1. Python Features

1.1 Collections:

  • List [1,2,3] - mutable
  • Tuple (1,2,3) - immutable
  • Set {1,2,3} - mutable
  • Dict {“A”:1, “B”: 2, “C”: 3} - mutable

1.2 Loops:

1.2.1 For-Loops:

for city in cities:
  print(city)

1.2.2 For with Range:

for i in range(5, 10):
  print("Bu {0} test".format(i))

1.2.3 For with Dicts:

for key, value in colors.items():
  print(f"{key} => {value}")

1.2.4 While:

c = 5
while c:
  print(c)
  c -= 1

1.2.5 List Comprehensions:

f = [len(word) for word in words]

1.2.6 Set Comprehensions:

s = {len(str(factorial(x))) for x in range(20)}

1.2.7 Dict Comprehensions:

s = {
  key_expr(item): value_expr(item)
  for item in iterable
}

1.2.8. Filter Comprehensions:

f = [len(word) for word in words if is_prime(word)]

1.3 Scope:

Modularity:

folder/init.py

1.4 Exception:

try:
  ...
except (KeyError, TypeError) as e:
    pass    // ignore
    raise   AnotherError // like throw

1.5 *args and **kargs

https://www.programiz.com/python-programming/args-and-kwargs

Python *args (non-keyword arguments)

def adder(*num):
    sum = 0
    for n in num:
        sum = sum + n
    print("Sum:",sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
Python **kwargs (keyword arguments)
def intro(**data):
    print("\nData type of argument:",type(data))
    for key, value in data.items():
        print("{} is {}".format(key,value))

intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)
intro(Firstname="John", Lastname="Wood", Email="johnwood@nomail.com", Country="Wakanda", Age=25, Phone=9876543210)

1.6 Advanced Topics

2. Python Coding Style (PEP8.org)

  • Formatting
  • Whitespace
  • Naming
  • Tools
    • pylint
    • pycodestyle
  • Documentation (docstring, sphinx)
  • Type Hints
  • flake8 tool

2.1 Type Hint and Duck Typing

(ref: https://adamj.eu/tech/2021/05/18/python-type-hints-duck-typing-with-protocol/)

from typing import Protocol

class Quacker(Protocol):
    def quack(self) -> str:
        ...

class Duck:
    def quack(self) -> str:
        return "Quack."

class MegaDuck:
    def quack(self) -> str:
        return "QUACK!"

def sonorize(duck: Quacker) -> None:
    print(duck.quack())

sonorize(Duck())
sonorize(MegaDuck())

3. Concurrency:

4. Python Tools

4.1 Frameworks

4.1.1 Comparisons

4.2 Dependency Manager

  • pip
  • pypi server

4.3 Compilers

4.4 Http Client and Circuit Breaker

4.5 Logger ?

Custom Fields Context

4.6 Test Library (TDD)

4.7 Pipeline Tools

  • Code Analysis (SonarQube)
  • Code Coverage
  • Dependency vulnerabilities Check (snky)
  • Linter
  • Formatter

4.8. Editor (VS Code)

4.9 Monads

4.10 JSON Marshalling

5. Practice And Patterns

5.1 Clean Architecture

Free book about python clean architecture https://leanpub.com/clean-architectures-in-python Talk: https://www.youtube.com/watch?v=wtCQalq7L-E

6. Sources: