def test_auto_register(self): """ Using :py:func:`AutoRegister` to, well, auto-register classes. """ registry = ClassRegistry(attr_name='element') # Note that we declare :py:func:`AutoRegister` as the metaclass # for our base class. class BasePokemon(with_metaclass(AutoRegister(registry))): """ Abstract base class; will not get registered. """ @abstract_method def get_abilities(self): raise NotImplementedError() # noinspection PyClassHasNoInit class Sandslash(BasePokemon): """ Non-abstract subclass; will get registered automatically. """ element = 'ground' def get_abilities(self): return ['sand veil'] # noinspection PyClassHasNoInit class BaseEvolvingPokemon(with_metaclass(ABCMeta, BasePokemon)): """ Abstract subclass; will not get registered. """ @abstract_method def evolve(self): raise NotImplementedError() # noinspection PyClassHasNoInit class Ekans(BaseEvolvingPokemon): """ Non-abstract subclass; will get registered automatically. """ element = 'poison' def get_abilities(self): return ['intimidate', 'shed skin'] def evolve(self): return 'Congratulations! Your EKANS evolved into ARBOK!' self.assertListEqual( list(registry.items()), [ # Note that only non-abstract classes got registered. ('ground', Sandslash), ('poison', Ekans), ], )
def test_error_attr_name_missing(self): """ The registry doesn't have an ``attr_name``. """ registry = ClassRegistry() with self.assertRaises(ValueError): AutoRegister(registry)
def test_abstract_strict_definition(self): """ If a class has no unimplemented abstract methods, it gets registered. """ registry = ClassRegistry(attr_name='element') class FightingPokemon(metaclass=AutoRegister(registry)): element = 'fighting' self.assertListEqual( list(registry.items()), [ # :py:class:`FightingPokemon` does not define any # abstract methods, so it is not considered to be # abstract! ('fighting', FightingPokemon), ], )
class B2Provider(Command): subcommands_registry = ClassRegistry() def run(self, args, data_in): self.provider_authorize_account(**json.loads(data_in)) return {} def provider_authorize_account( self, *, provider_application_key_id, provider_application_key, provider_endpoint, **kwargs ): if not provider_application_key_id or not provider_application_key: raise RuntimeError('B2 Application Key and Application Key ID must be provided') self.api.authorize_account( provider_endpoint, provider_application_key_id, provider_application_key )
import logging import typing from datetime import datetime from abc import abstractmethod from class_registry import ClassRegistry from attributee import Attributee, Object, Integer, Float, Nested, List from vot.tracker import RealtimeTrackerRuntime, TrackerException from vot.utilities import Progress, to_number, import_class experiment_registry = ClassRegistry("vot_experiment") transformer_registry = ClassRegistry("vot_transformer") class RealtimeConfig(Attributee): grace = Integer(val_min=0, default=0) fps = Float(val_min=0, default=20) class NoiseConfig(Attributee): # Not implemented yet placeholder = Integer(default=1) class InjectConfig(Attributee): # Not implemented yet placeholder = Integer(default=1)
from class_registry import ClassRegistry, ClassRegistryInstanceCache metadata_controllers = ClassRegistry('kind') cached_metadata_controllers = ClassRegistryInstanceCache(metadata_controllers) class MetadataController(object): """Metadata Controller class represents a kind of metadata.""" @property def kind(self): """Kind is a reverse domain id for a metadata.""" raise NotImplementedError() @property def serializer(self): """Serializer is an instantiated serializer.""" raise NotImplementedError()
from .scripts.azul import cli from .base_price_manager import BasePriceManager import pathlib from datetime import datetime """ Some global vars. """ name = 'azul' __all__ = [ 'get_price_data', 'BaseSymbolFetcher', 'cli', 'BasePriceManager', 'FORMAT_YMD', 'price_manager_registry', 'symbol_fetcher_registry', 'update_price_data' ] symbol_fetcher_registry = ClassRegistry() from .faang_symbol_fetcher import FaangSymbolFetcher from .sp500_wikipedia_symbol_fetcher import SP500WikipediaSymbolFetcher price_manager_registry = ClassRegistry() from .polygon_price_manager import PolygonPriceManager from .iex_price_manager import IEXPriceManager FORMAT_YMD = '%Y-%m-%d' def get_price_data(symbol_source: str, data_source: str, output_dir: str, start: datetime, end: datetime) -> None: """ Gets symbols, downloads minute data, generates daily data, and stores it in output_dir.
import importlib from cachetools import Cache from class_registry import ClassRegistry from attributee import Attributee, String from vot import ToolkitException from vot.tracker import Tracker from vot.dataset import Sequence from vot.experiment import Experiment from vot.region import Region, RegionType from vot.utilities import class_fullname, arg_hash from vot.utilities.data import Grid analysis_registry = ClassRegistry("vot_analysis") class MissingResultsException(ToolkitException): """Exception class that denotes missing results during analysis """ pass class Sorting(Enum): """Sorting direction enumeration class """ UNSORTABLE = auto() DESCENDING = auto() ASCENDING = auto() class Axes(Enum): """Semantic information for axis in analysis grid
import unittest from class_registry import ClassRegistry from class_registry import RegistryKeyError animal_registry = ClassRegistry() class Animal(object): def speak(self): raise NotImplementedError @animal_registry.register('dog') class Dog(Animal): def __init__(self, param1): self.param1 = param1 def speak(self): return 'Bark' + ' ' + self.param1 @animal_registry.register('cat') class Cat(Animal): def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2 def speak(self): return 'Meow' + ' ' + self.param1 + ' ' + self.param2
from typing import List from pandas import DataFrame from class_registry import ClassRegistry from data.data_class_types import DataclassTypes from data.normalized_data import NormalizedData registered_converters = ClassRegistry("provider", unique=True) def convert_list(bulk: List) -> List[NormalizedData]: normalized_data_list = [] df = DataFrame(obj.to_doc() for obj in bulk) for provider_type in DataclassTypes: normalized_data_list.extend( registered_converters.get(provider_type).convert_dataframe( df[df["_cls"] == provider_type])) return normalized_data_list
from abc import abstractmethod import numpy as np from class_registry import AutoRegister, ClassRegistry, ClassRegistryInstanceCache _registry = ClassRegistry('name') skeleton_registry = ClassRegistryInstanceCache(_registry) class Skeleton(metaclass=AutoRegister(_registry)): name = object() @abstractmethod def __init__(self, joint_names, joint_tree, hflip_indices): """Description of a particular skeleton representation. Args: joint_names (list of str): Names of the joints. joint_tree (list of int): References to the parent of each joint. hflip_indices (list of int): References to the horizontal mirror of each joint. """ assert len(joint_names) == len(joint_tree) == len(hflip_indices) self.joint_names = joint_names self.joint_tree = joint_tree self.hflip_indices = hflip_indices self.kcs_matrix_c = self._build_kcs_matrix_c() def _build_kcs_matrix_c(self): bone_descs = [] for t, r in enumerate(self.joint_tree): if t != r:
from itertools import chain from unidecode import unidecode from class_registry import ClassRegistry, ClassRegistryInstanceCache import click import pathspec from slugify import slugify from colorama import Fore, Style logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(message)s')) logger.addHandler(handler) logger.setLevel(logging.INFO) linterdex = ClassRegistry('name') class TestBase(): """Base class for file tests.""" def __init__(self): # noqa: D107 self.failed = [] self.ok = [] self.total = 0 # count total of tests performed def add_failed(self, path): """Mark the given path as failed.""" self.failed.append(path) def add_ok(self, path): """Mark the given path as ok."""
from abc import ABC, abstractmethod from typing import Union from aioreactive.core.streams import AsyncMultiStream from class_registry import ClassRegistry from hausnet.devices import NodeDevice, BasicSwitch, CompoundDevice, Device, SubDevice, RootDevice, Sensor from hausnet.operators.operators import HausNetOperators as Op from hausnet.flow import * from hausnet.plant import DeviceAssembly, DevicePlant from hausnet.states import FloatState, State log = logging.getLogger(__name__) builders = ClassRegistry() class DeviceBuilder(ABC): """Builds a specific device from configuration. Each concrete device type should have a corresponding builder.""" @abstractmethod def from_blueprint(self, plant: DevicePlant, blueprint: Dict[str, Any], owner: CompoundDevice = None) \ -> DeviceAssembly: """ Given a structured build blueprint, build a device assembly. :param plant: The device plant the assembly is being added to. :param blueprint: A dictionary containing the config values in the format above. :param owner: The owner of this device, if any. :returns: A completed device assembly, with a device of the type the builder builds. """ pass
from class_registry import ClassRegistry auxiliary_parameter_registry = ClassRegistry("_auxiliary_sampler_name") distribution_registry = ClassRegistry("_distribution_name") selection_registry = ClassRegistry("_selection_name") def list_available_distributions(): for k, v in distribution_registry.items(): print(k) def list_available_selection_functions(): for k, v in selection_registry.items(): print(k) def list_available_auxiliary_samplers(): for k, v in auxiliary_parameter_registry.items(): print(k) __all__ = [ "auxiliary_parameter_registry", "distribution_registry", "distribution_registry",
from __future__ import annotations import json from abc import ABC from dataclasses import dataclass, asdict, field from typing import Dict, Optional from bson import ObjectId, json_util from class_registry import ClassRegistry from data.data_class_types import DataclassTypes data_types = ClassRegistry("_cls", unique=True) @dataclass class _BaseData(ABC): _id: Optional[ObjectId] = field(init=False, default=None) _cls: DataclassTypes = field(init=False) @property def uid(self) -> ObjectId: return self._id @uid.setter def uid(self, uid: ObjectId) -> None: self._id = uid def to_doc(self) -> Dict: raw_data_doc = asdict(self).copy() if self._id is None:
import abc from class_registry import ClassRegistry from invoicer.invoices.models import Invoice payment_registry = ClassRegistry(attr_name="label", unique=True) class BasePaymentController(abc.ABC): # идентификатор платежной системы в реестре label = "" # определяет, доступна ли платежная система для использования is_enabled = True # ссылка на домашнюю страницу domestic_url = "" def get_payment_url(self, invoice: Invoice): """ Возвращает ссылку для оплаты для счета invoice """ raise NotImplementedError
from libshipkore.common.baseservice import BaseService from class_registry import ClassRegistry from ..models.model import Track track_registry = ClassRegistry() class BaseTrackService(BaseService): def _get_data(self): return self.__data def _set_data(self, value): self.__data = Track(**value) if value else None data = property(_get_data, _set_data) def __init__(self, waybill, provider, *args, **kwargs): super().__init__(waybill, provider, *args, **kwargs) self.waybill = waybill self.provider = provider def _fetch(self): raise NotImplementedError def _transform(self): raise NotImplementedError def _save(self): pass def get(self):
class registry: algorithm = ClassRegistry(attr_name="__new__") policy = ClassRegistry(attr_name="__new__") buffer = ClassRegistry(attr_name="__new__")