aiogram/aiogram/utils/mixins.py

51 lines
1.3 KiB
Python
Raw Normal View History

import contextvars
2018-12-31 23:05:44 -05:00
from typing import TypeVar, Type
__all__ = ('DataMixin', 'ContextInstanceMixin')
class DataMixin:
@property
def data(self):
data = getattr(self, '_data', None)
if data is None:
data = {}
setattr(self, '_data', data)
return data
def __getitem__(self, item):
return self.data[item]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
def __contains__(self, key):
return key in self.data
def get(self, key, default=None):
return self.data.get(key, default)
2018-12-31 23:05:44 -05:00
T = TypeVar('T')
class ContextInstanceMixin:
def __init_subclass__(cls, **kwargs):
2019-07-22 00:11:06 +03:00
cls.__context_instance = contextvars.ContextVar(f'instance_{cls.__name__}')
return cls
@classmethod
2018-12-31 23:05:44 -05:00
def get_current(cls: Type[T], no_error=True) -> T:
if no_error:
return cls.__context_instance.get(None)
return cls.__context_instance.get()
@classmethod
2018-12-31 23:05:44 -05:00
def set_current(cls: Type[T], value: T):
if not isinstance(value, cls):
2019-07-22 00:11:06 +03:00
raise TypeError(f'Value should be instance of {cls.__name__!r} not {type(value).__name__!r}')
cls.__context_instance.set(value)