Skip to content

Instantly share code, notes, and snippets.

View mahenzon's full-sized avatar

Suren Khorenyan mahenzon

View GitHub Profile
@mahenzon
mahenzon / example_callback_protocol.py
Created February 2, 2025 11:57
Protocol annotation in Python
from typing import Protocol
class MessageCallback(Protocol):
__name__: str
def __call__(
self,
message: str,
size: int,
@mahenzon
mahenzon / common.py
Created January 26, 2025 06:58
overload annotation in Python
import logging
# DEFAULT_LOG_FORMAT = "[%(asctime)s.%(msecs)03d] %(funcName)20s %(module)s:%(lineno)d %(levelname)-8s - %(message)s"
DEFAULT_LOG_FORMAT = (
"%(funcName)10s %(module)s:%(lineno)d %(levelname)-8s - %(message)s"
)
def configure_logging(level: int = logging.INFO) -> None:
logging.basicConfig(
@mahenzon
mahenzon / replace-shadow-hash.py
Created January 22, 2025 06:39
Python script to replace password for macOS user if you have sudo rights
"""
Tested on macOS 11.5 Big Sur
SIP disabled
admin@MBP-Suren ~ % csrutil status
System Integrity Protection status: disabled.
run:
@mahenzon
mahenzon / pyproject.toml
Created December 22, 2024 08:19
Self type annotation in Python
[tool.mypy]
strict = true
@mahenzon
mahenzon / python-defaultdict-examples.py
Created December 7, 2024 18:07
Python defaultdict examples
# SOME_SENTENCE = input("Enter a sentence: ")
from collections import defaultdict
from collections.abc import Iterable
SOME_SENTENCE = (
"The cat sat on the mat, "
"and the cat played with the mat "
"while the cat watched the sun."
)
@mahenzon
mahenzon / common.py
Created November 30, 2024 20:08
Annotation for decorator creator in Python
import logging
# DEFAULT_LOG_FORMAT = "[%(asctime)s.%(msecs)03d] %(funcName)20s %(module)s:%(lineno)d %(levelname)-8s - %(message)s"
DEFAULT_LOG_FORMAT = (
"%(funcName)10s %(module)s:%(lineno)d %(levelname)-8s - %(message)s"
)
def configure_logging(level: int = logging.INFO) -> None:
logging.basicConfig(
@mahenzon
mahenzon / pyproject.toml
Created November 16, 2024 17:24
Generic classes in Python
[tool.mypy]
strict = true
@mahenzon
mahenzon / pyproject.toml
Created October 27, 2024 13:08
Generic Python annotation examples
[tool.mypy]
strict = true
@mahenzon
mahenzon / example_01_intro.py
Created October 27, 2024 05:26
TypeVar examples
from typing import TypeVar, Sequence
T = TypeVar("T")
def repeat(val: T, times: int) -> list[T]:
return [val] * times
def get_first_element(items: Sequence[T]) -> T:
@mahenzon
mahenzon / service.py
Created October 21, 2024 10:04
Action Service example
"""
Based on https://github.com/tough-dev-school/education-backend/blob/master/src/core/services.py
"""
from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
from typing import Any, Generic, TypeVar
ReturnType = TypeVar('ReturnType')