function definition_
def fn(): def fn() -> None: procedure with no arguments
def fn(x, y): def fn(x:Type, y:Type) -> Type: simple function
def fn(x='value', y) def fn(x:Type='value', y:Type) -> Type function with default values
def fn(x, *args, **kwargs) function with positional and keyword arguments
comprehensions
[fn(var) for var in input_list if clause] list comprehension, if is optional
{var:fn(var) for var in input_list if clause} dict comprehension, if is optional
{fn(var) for var in input_list if clause} set comprehension, if is optional
(fn(var) for var in input_list if clause) generator comprehension, if is optional
json
import json importing the library
dict_string=json.dumps(my_dict) convert Python object to JSON string
dict_pretty_string=json.dumps(my_dict,indent=4) convert Python object to JSON string, but making it pretty

with open("file.json", "w") as json_file:
    json.dump(my_dict, json_file, indent=4)
write JSON data to a file

with open("file.json", "r") as json_file:
    loaded_my_dict = json.load(json_file)
read JSON data from a file
loaded_my_dict_from_str = json.loads(dict_string) convert JSON string back to Python object
requests
import requests importing the library

response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
if response.status_code == 200:
    print("GET:", response.json())
GET Request: Fetch data from a server

payload = {"key1": "value1", "key2": "value2"}
response = requests.post("https://httpbin.org/post", data=payload)
if response.status_code == 200:
    print("POST:", response.json()["form"])
POST Request: Send data to a server

headers = {"User-Agent": "my-app"}
response = requests.get("https://httpbin.org/get", headers=headers)
if response.status_code == 200:
    print("HEADERS:", response.json()["headers"])
sending Headers: Add HTTP headers to your request

try:
    response = requests.get("https://httpbin.org/delay/10", timeout=5)
except requests.exceptions.Timeout:
    print("Timeout occurred")
Timeout: Specify a timeout for the request

with requests.Session() as session:
    session.get("https://httpbin.org/cookies/set/sessioncookie/123456")
    response = session.get("https://httpbin.org/cookies")
    print("SESSION:", response.json()["cookies"])
Session: Create a session for multiple requests

files = {"file": open("test.txt", "rb")}
response = requests.post("https://httpbin.org/post", files=files)
if response.status_code == 200:
    print("FILE UPLOAD:", response.json()["files"])
File Upload: Upload a file to a server

response = requests.get("https://httpbin.org/status/404")
response.raise_for_status() # Raises HTTPError for bad responses
Error Handling: Catch and handle HTTP errors
regular expressions
def fn(): def fn() -> None: procedure with no arguments
fastapi
def fn(): def fn() -> None: procedure with no arguments
sqlalchemy
def fn(): def fn() -> None: procedure with no arguments
variable scope
Local variable_name = 1
Global global variable_name = 1
Non Local nonlocal variable_name = 1
class definition

class Animal:
    species = "Unknown"  # Class Variable
    def __init__(self, name):  # Instance Constructor 
        self.name = name
    def describe(self):  # Instance Method
        return f"{self.name} is a {self.species}"
    @staticmethod
    def is_alive(lifespan, current_age):  # Static Method
        return current_age < lifespan
    @classmethod
    def set_species(cls, new_species):  # Class Method 
        cls.species = new_species
sets
s = {1, 2, 3} Creation of a set
s & z s.__and__(z) Intersection of s and z
s &= z s.__iand__(z) s updated with intersection of s and z
s | z s.__or__(z) Union of s and z
s |= z s.__ior__(z) s updated with union of s and z
dictionary wih default values

import collections
my_dict, key, new_value = {}, "key", 1
# using defaultdict
coll = collections.defaultdict(list)
coll[key].append(new_value)
# using setdefault
my_dict.setdefault("key", []).append(new_value)
if key not in my_dict:
    my_dict[key] = []
my_dict[key].append(new_value)
dataclasses
Local variable_name = 1
typing
Local variable_name = 1
exceptions
Local variable_name = 1
logging
Local variable_name = 1
pydantic
Local variable_name = 1
jinja2
Local variable_name = 1
missing
ElementTree parse XML trees
asyncio asynchronous functionality
poetry
lambda
reduce another functools function
partial Partial functions
mypy Cheching types
pytest Testing
decorators
time Managing time
class inheritance

class Dog(Animal):
    # Override class variable
    species = "Canine"
    # Overide and extend
    def __init__(self, n, breed): 
        super().__init__(n) 
        self.breed = breed
        
    # Additional instance method
    def fetch(self, thing):
        return f"{self.name} fetched the {thing}"
class properties

class Person:
    def __init__(self, name, age):
        self.name = name
        self._age = age 
    @property
    def age(self):
        return self._age
    @age.setter
    def age(self, value):
        if value < 0:
            print("Age cannot be negative!")
        else:
            self._age = value
abstract class

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
boilerplate main

if __name__ == "__main__":
    main()
expression operators

yield x
Generator function send protocol

lambda args: expression
Anonymous function generation

x if y else z
Ternary operation

x or y
Logical OR

x and y
Logical AND

not x
Logical negation

x in y
x not in y
Membership(iterables, sets)

x is y
x is not y
Object identity test

x < y
x <= y
x > y
x >= y
Magnitude comparison, set subset and superset

x == y
x != y
Value equality operators

x | y
Bitwise OR, set union

x ^ y
Bitwise XOR, set symmetric difference

x & y
Bitwise AND, set intersection

x << y
x >> y
Shift x left or right by y bits

x + y
Addition, concatenation

x - y
Subtraction, set difference

x * y
Multiplication, repetition

x % y
Remainder, format

x / y
x // y
Division: true and floor

-x
Negation

~x
Bitwise NOT (inversion)

x ** y
Power (exponentiation)