Skip to main content

Python

Access attribute using string

getattr(object, name, default=None)
hasattr(object, name)

pip - PIP Installs Packages

Reference

CLI

pip
python -m pip

Install package

pip install <package>

Uninstall package

pip uninstall <package>

List installed package

pip list

Download package

pip download <package>

Install downloaded package

pip install --no-index --find-links <directory> <package>

Export requirements.txt

pip freeze > requirements.txt

Install requirements.txt

pip install -r requirements.txt

Download requirements.txt

pip download -r requirements.txt

Formatter

Unit test

pytest reference / Reference

module/
lib/
__init__.py
module.py
tests/
test_module.py
# test_module.py

import unittest
from lib import module

class TestModule(unittest.TestCase):
def test_module(self):
pass

if __name__ == '__main__':
unittest.main()
# In /module/ folder
python -m tests.test_module

Unit test framework

Show sys.path (module path) in CLI

python -m site

Pass all arguments to another function

class List(list):
def append_twice(self, *args, **kwargs):
self.append(*args, **kwargs)
self.append(*args, **kwargs)

Decorator

Reference

@decorator
def run():
pass

is equivalent to

def run():
pass
run = decorator(run)
from functools import wraps

def decorator(func):
# Using original func name and doc string
@wraps(func)
def wrap():
print("[Before]")
func()
print("[After]")
return wrap

@decorator
def run():
print("Run")

run()

# [Before]
# Run
# [After]

Bind self to function

Reference

import types

def power(self, exp):
return pow(self, exp)

power2 = types.MethodType(power, 2)
print(power2(8)) # 256

Follow file

Follow file changed / appended data

from io import SEEK_CUR, SEEK_END, SEEK_SET
from typing import Iterator, TextIO
import sys


def follow(file: TextIO, interval: float = 0.2) -> Iterator[str]:
from time import sleep
line = ''
while True:
new = file.readline()
if new == "":
sleep(interval)
continue
line += new
if not line.endswith("\n"):
continue
yield line[:-1]
line = ''


if __name__ == '__main__':
with open("access.log", 'r') as file:
file.seek(0, SEEK_END)
for line in follow(file):
print(line)

Is iterable ?

from collections.abc import Iterable

isinstance(e, Iterable):