|
| 1 | +# Copyright 2024-2025 Open Quantum Design |
| 2 | + |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | + |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +import inspect |
| 17 | +import warnings |
| 18 | +from abc import ABC, abstractmethod |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +######################################################################################## |
| 22 | + |
| 23 | +__all__ = [ |
| 24 | + "MetaBackendRegistry", |
| 25 | + "BackendRegistry", |
| 26 | + "BackendBase", |
| 27 | +] |
| 28 | + |
| 29 | +######################################################################################## |
| 30 | + |
| 31 | + |
| 32 | +class MetaBackendRegistry(type): |
| 33 | + def __new__(cls, clsname, superclasses, attributedict): |
| 34 | + attributedict["backends"] = dict() |
| 35 | + return super().__new__(cls, clsname, superclasses, attributedict) |
| 36 | + |
| 37 | + def register(cls, backend): |
| 38 | + if not issubclass(backend, BackendBase): |
| 39 | + raise TypeError("You may only register subclasses of BackendBase.") |
| 40 | + |
| 41 | + if backend.__name__ in cls.backends.keys(): |
| 42 | + warnings.warn("Overiding previously registered backend with the same name.") |
| 43 | + |
| 44 | + cls.backends[backend.__name__] = backend |
| 45 | + |
| 46 | + |
| 47 | +class BackendRegistry(metaclass=MetaBackendRegistry): |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +class BackendBase(ABC): |
| 52 | + @abstractmethod |
| 53 | + def run(self, program, args): |
| 54 | + pass |
| 55 | + |
| 56 | + def __init_subclass__(cls): |
| 57 | + super().__init_subclass__() |
| 58 | + |
| 59 | + args = inspect.getfullargspec(cls.run) |
| 60 | + |
| 61 | + if "program" not in args.annotations: |
| 62 | + warnings.warn( |
| 63 | + f"Misisng type hint for argument `program` in run method of {cls.__name__}. Defaults to Any." |
| 64 | + ) |
| 65 | + |
| 66 | + cls.run.__annotations__["program"] = Any |
| 67 | + |
| 68 | + if "args" not in args.annotations: |
| 69 | + warnings.warn( |
| 70 | + f"Misisng type hint for argument `args` in run method of {cls.__name__}. Defaults to Any." |
| 71 | + ) |
| 72 | + |
| 73 | + cls.run.__annotations__["args"] = Any |
| 74 | + |
| 75 | + BackendRegistry.register(cls) |
0 commit comments