Skip to content

Instantly share code, notes, and snippets.

@funketh
funketh / function_to_method.py
Created December 3, 2019 22:09
Decorator to add functions as methods to a class (Note: This is basically useless as you can just use `method_name = function` inside the class body)
from typing import TypeVar, Union, Callable, Optional
_ClsT = TypeVar('_ClsT', bound=type)
def add_method(func: Union[Callable, classmethod, staticmethod],
name: Optional[str] = None) -> Callable[[_ClsT], _ClsT]:
"""Class decorator that adds the given function as a method to the class"""
@funketh
funketh / topic_manager.py
Last active March 19, 2019 20:58
Basic subscriber/ publisher pattern implementation
import logging
from collections import defaultdict
class TopicManager:
def __init__(self):
self.subscribers = defaultdict(set)
def subscribe(self, topic, callback):
"""Subscribes a callback function to a topic"""
@funketh
funketh / curryable.py
Last active November 10, 2019 21:36
currying decorator in python
from functools import wraps, partial
from inspect import signature
def curryable(func):
@wraps(func)
def curryable_func(*args, **kwargs):
try:
signature(func).bind(*args, **kwargs)
except TypeError: