├── tests ├── __init__.py ├── test_impler.py ├── conftest.py ├── test_input_validation.py ├── test_impl_methods.py └── test_impl_interface.py ├── .flake8 ├── impler ├── exceptions.py ├── __init__.py └── main.py ├── .pre-commit-config.yaml ├── pyproject.toml ├── docs └── api.md ├── README.md ├── .gitignore ├── LICENSE └── assets ├── logo.svg └── logo_sharp.svg /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E501, W503 3 | per-file-ignores = tests/*:F811 -------------------------------------------------------------------------------- /impler/exceptions.py: -------------------------------------------------------------------------------- 1 | class ImplException(Exception): 2 | """ 3 | Base exception class 4 | """ 5 | 6 | pass 7 | -------------------------------------------------------------------------------- /tests/test_impler.py: -------------------------------------------------------------------------------- 1 | from impler import __version__ 2 | 3 | 4 | def test_version(): 5 | assert __version__ == "0.2.0" 6 | -------------------------------------------------------------------------------- /impler/__init__.py: -------------------------------------------------------------------------------- 1 | from impler.main import ( 2 | impl, 3 | impl_classmethod, 4 | impl_staticmethod, 5 | impl_interface, 6 | ) 7 | 8 | __version__ = "0.2.0" 9 | 10 | __all__ = ["impl", "impl_classmethod", "impl_staticmethod", "impl_interface"] 11 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture() 5 | def Cls(): 6 | class A: 7 | outer = 0 8 | 9 | def __init__(self): 10 | self.internal = 0 11 | 12 | def exists(self): 13 | return 0 14 | 15 | return A 16 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/ambv/black 3 | rev: 20.8b1 4 | hooks: 5 | - id: black 6 | language_version: python3.9 7 | - repo: https://gitlab.com/pycqa/flake8 8 | rev: 3.9.2 9 | hooks: 10 | - id: flake8 11 | - repo: https://github.com/pre-commit/mirrors-mypy 12 | rev: v0.910 13 | hooks: 14 | - id: mypy 15 | additional_dependencies: 16 | - types-click 17 | - types-toml 18 | exclude: ^tests/ 19 | 20 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "impler" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Roman "] 6 | license = "Apache-2.0" 7 | homepage = "https://github.com/roman-right/impler" 8 | repository = "https://github.com/roman-right/impler" 9 | keywords = ["impl", "impler", "implementation", "pattern", "sync", "async", "python"] 10 | include = [ 11 | "LICENSE", 12 | ] 13 | readme = "README.md" 14 | 15 | [tool.poetry.dependencies] 16 | python = ">=3.7,<4.0" 17 | asyncio = "^3.4" 18 | 19 | [tool.poetry.dev-dependencies] 20 | pytest = "^6.0" 21 | pytest-asyncio = "^0.17.0" 22 | pytest-cov = "^3.0.0" 23 | pydoc-markdown = "^4.5.0" 24 | 25 | [build-system] 26 | requires = ["poetry-core>=1.0.0"] 27 | build-backend = "poetry.core.masonry.api" 28 | 29 | [tool.pytest.ini_options] 30 | minversion = "6.0" 31 | addopts = "--cov-report term-missing --cov=impler --cov-branch --cov-fail-under=85" 32 | testpaths = [ 33 | "tests", 34 | ] 35 | filterwarnings = [ 36 | "error", 37 | "ignore::DeprecationWarning", 38 | "ignore::UserWarning", 39 | ] 40 | 41 | [tool.black] 42 | line-length = 79 43 | include = '\.pyi?$' 44 | exclude = ''' 45 | /( 46 | \.git 47 | | \.hg 48 | | \.mypy_cache 49 | | \.tox 50 | | \.venv 51 | | _build 52 | | buck-out 53 | | build 54 | | dist 55 | )/ 56 | ''' -------------------------------------------------------------------------------- /tests/test_input_validation.py: -------------------------------------------------------------------------------- 1 | from typing import Type 2 | 3 | import pytest 4 | 5 | from impler import impl 6 | from impler.exceptions import ImplException 7 | 8 | 9 | def test_incompatible_type(Cls): 10 | with pytest.raises(ImplException): 11 | 12 | @impl(Cls, as_parent=True) 13 | def plus_ten(cls: Type[Cls]): 14 | cls.outer += 10 15 | 16 | with pytest.raises(ImplException): 17 | 18 | @impl(Cls, copy_protected=True) 19 | def plus_ten(cls: Type[Cls]): 20 | cls.outer += 10 21 | 22 | with pytest.raises(ImplException): 23 | 24 | @impl(Cls, copy_magic=True) 25 | def plus_ten(cls: Type[Cls]): 26 | cls.outer += 10 27 | 28 | with pytest.raises(ImplException): 29 | 30 | @impl(Cls, as_classmethod=True, as_staticmethod=True) 31 | def plus_ten(cls: Type[Cls]): 32 | cls.outer += 10 33 | 34 | with pytest.raises(ImplException): 35 | 36 | @impl(Cls, as_classmethod=True) 37 | @classmethod 38 | def plus_ten(cls: Type[Cls]): 39 | cls.outer += 10 40 | 41 | with pytest.raises(ImplException): 42 | 43 | @impl(Cls, as_staticmethod=True) 44 | class Interface: 45 | ... 46 | 47 | with pytest.raises(ImplException): 48 | 49 | @impl(Cls, as_classmethod=True) 50 | class Interface: 51 | ... 52 | 53 | with pytest.raises(ImplException): 54 | 55 | @impl(Cls, as_parent=True, copy_magic=True) 56 | class Interface: 57 | ... 58 | 59 | with pytest.raises(ImplException): 60 | 61 | @impl(Cls, as_parent=True, copy_protected=True) 62 | class Interface: 63 | ... 64 | -------------------------------------------------------------------------------- /tests/test_impl_methods.py: -------------------------------------------------------------------------------- 1 | from typing import Type 2 | 3 | import pytest 4 | 5 | from impler import impl, impl_classmethod, impl_staticmethod 6 | from impler.main import impl_method 7 | 8 | pytestmark = pytest.mark.asyncio 9 | 10 | 11 | def test_impl_method(Cls): 12 | @impl_method(Cls) 13 | def set_ten(self): 14 | self.internal = 10 15 | 16 | a = Cls() 17 | a.set_ten() 18 | assert a.internal == 10 19 | 20 | 21 | def test_sync_method(Cls): 22 | @impl(Cls) 23 | def set_ten(self): 24 | self.internal = 10 25 | 26 | a = Cls() 27 | a.set_ten() 28 | assert a.internal == 10 29 | 30 | 31 | def test_sync_classmethod(Cls): 32 | @impl_classmethod(Cls) 33 | def set_ten(cls: Type[Cls]): 34 | cls.outer = 10 35 | 36 | Cls.set_ten() 37 | assert Cls.outer == 10 38 | 39 | @impl(Cls) 40 | @classmethod 41 | def plus_ten(cls: Type[Cls]): 42 | cls.outer += 10 43 | 44 | Cls.plus_ten() 45 | assert Cls.outer == 20 46 | 47 | 48 | def test_sync_staticmethod(Cls): 49 | @impl_staticmethod(Cls) 50 | def get_ten(): 51 | return 10 52 | 53 | assert Cls.get_ten() == 10 54 | 55 | @impl(Cls) 56 | @staticmethod 57 | def get_zero(): 58 | return 0 59 | 60 | assert Cls.get_zero() == 0 61 | 62 | 63 | async def test_async_method(Cls): 64 | @impl(Cls) 65 | async def set_ten(self: Cls): 66 | self.internal = 10 67 | 68 | a = Cls() 69 | await a.set_ten() 70 | assert a.internal == 10 71 | 72 | 73 | async def test_async_classmethod(Cls): 74 | @impl_classmethod(Cls) 75 | async def set_ten(cls: Type[Cls]): 76 | cls.outer = 10 77 | 78 | await Cls.set_ten() 79 | assert Cls.outer == 10 80 | 81 | @impl(Cls) 82 | @classmethod 83 | async def plus_ten(cls: Type[Cls]): 84 | cls.outer += 10 85 | 86 | await Cls.plus_ten() 87 | assert Cls.outer == 20 88 | 89 | 90 | async def test_async_staticmethod(Cls): 91 | @impl_staticmethod(Cls) 92 | async def get_ten(): 93 | return 10 94 | 95 | assert await Cls.get_ten() == 10 96 | 97 | @impl(Cls) 98 | @staticmethod 99 | async def get_zero(): 100 | return 0 101 | 102 | assert await Cls.get_zero() == 0 103 | 104 | 105 | def test_override(Cls): 106 | c = Cls() 107 | 108 | @impl(Cls) 109 | def exists(self): 110 | return 100 111 | 112 | assert c.exists() == 0 113 | 114 | @impl(Cls, override=True) 115 | def exists(self): 116 | return 100 117 | 118 | assert c.exists() == 100 119 | -------------------------------------------------------------------------------- /docs/api.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # impler.main 4 | 5 | 6 | 7 | ## impl Objects 8 | 9 | ```python 10 | class impl() 11 | ``` 12 | 13 | Decorator. 14 | 15 | Implementation of a method or of an interface for the classes. 16 | 17 | 18 | 19 | #### \_\_init\_\_ 20 | 21 | ```python 22 | def __init__(target: Type, *, override: bool = False, as_parent: bool = False, copy_protected: bool = False, copy_magic: bool = False, as_classmethod: bool = False, as_staticmethod: bool = False) 23 | ``` 24 | 25 | Init 26 | 27 | **Arguments**: 28 | 29 | For all: 30 | - `target` - Type 31 | - `override` - bool - should exist attributes and methods be overridden 32 | For interfaces: 33 | - `as_parent` - bool - inject interface as a parent 34 | - `copy_protected` - bool - copy protected fields *[Works only with inject_parent is Flase]* 35 | - `copy_magic` - bool - copy magic methods and attributes *[Works only with inject_parent is Flase]* 36 | For methods: 37 | - `as_classmethod` - bool - set method as a class method 38 | - `as_staticmethod` - bool - set method as a static method 39 | 40 | 41 | 42 | #### impl\_method 43 | 44 | ```python 45 | def impl_method(target: Type, *, override: bool = False, as_classmethod: bool = False, as_staticmethod: bool = False) 46 | ``` 47 | 48 | Decorator. 49 | Set function as a method of the given class (regular, classmethod or staticmethod) 50 | 51 | **Arguments**: 52 | 53 | - `target` - Type 54 | - `override` - bool - should exist method be overridden 55 | - `as_classmethod` - bool - set method as a class method 56 | - `as_staticmethod` - bool - set method as a static method 57 | 58 | 59 | 60 | #### impl\_classmethod 61 | 62 | ```python 63 | def impl_classmethod(target: Type, *, override: bool = False) 64 | ``` 65 | 66 | Decorator. 67 | Set function as a classmethod of the given class 68 | 69 | **Arguments**: 70 | 71 | - `target` - Type 72 | - `override` - bool - should exist method be overridden 73 | 74 | 75 | 76 | #### impl\_staticmethod 77 | 78 | ```python 79 | def impl_staticmethod(target: Type, *, override: bool = False) 80 | ``` 81 | 82 | Decorator. 83 | Set function as a staticmethod of the given class 84 | 85 | **Arguments**: 86 | 87 | - `target` - Type 88 | - `override` - bool - should exist method be overridden 89 | 90 | 91 | 92 | #### impl\_interface 93 | 94 | ```python 95 | def impl_interface(target: Type, *, override: bool = False, as_parent: bool = False, copy_protected: bool = False, copy_magic: bool = False) 96 | ``` 97 | 98 | **Arguments**: 99 | 100 | - `target` - Type 101 | - `override` - bool - should exist attributes and methods be overridden 102 | - `as_parent` - bool - inject interface as a parent 103 | - `copy_protected` - bool - copy protected fields [Works only with inject_parent == Flase] 104 | - `copy_magic` - bool - copy magic methods and attributes [Works only with inject_parent == Flase] 105 | 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Implementation pattern *(inspired by Rust)* 2 | 3 | Useful when it is needed to extend a class (usually 3d party) with some methods 4 | or interfaces 5 | 6 | ![](https://raw.githubusercontent.com/roman-right/impler/main/assets/logo.svg) 7 | 8 | *Please, be careful. This library is literally a class patcher.* 9 | 10 | ## Install 11 | 12 | ```shell 13 | pip install impler 14 | ``` 15 | 16 | or 17 | 18 | ```shell 19 | poetry add impler 20 | ``` 21 | 22 | ## Usage 23 | 24 | ### Methods implementation 25 | 26 | Using implementation pattern you can extend any class (even 3rd party) with 27 | regular, class or static methods. 28 | 29 | ```python 30 | from impler import impl 31 | from pydantic import BaseModel 32 | 33 | 34 | @impl(BaseModel) 35 | def fields_count(self: BaseModel): 36 | return len(self.__fields__) 37 | 38 | 39 | class Point(BaseModel): 40 | x: int = 0 41 | y: int = 1 42 | 43 | 44 | point = Point() 45 | print(point.fields_count()) 46 | ``` 47 | 48 | Class methods 49 | 50 | ```python 51 | @impl_classmethod(BaseModel) 52 | def fields_count(cls): 53 | return len(cls.__fields__) 54 | 55 | 56 | # or 57 | 58 | @impl(BaseModel) 59 | @classmethod 60 | def fields_count(cls): 61 | return len(cls.__fields__) 62 | ``` 63 | 64 | Static methods 65 | 66 | ```python 67 | @impl_staticmethod(BaseModel) 68 | def zero(cls): 69 | return 0 70 | 71 | 72 | # or 73 | 74 | @impl(BaseModel) 75 | @staticmethod 76 | def zero(cls): 77 | return 0 78 | ``` 79 | 80 | Async methods 81 | 82 | ```python 83 | @impl(BaseModel) 84 | async def zero(cls): 85 | await asyncio.sleep(1) 86 | return 0 87 | ``` 88 | 89 | ### Interfaces implementation 90 | 91 | The same way you can extend any class with the whole interface 92 | 93 | Here is example of the base interface 94 | 95 | ```python 96 | from pathlib import Path 97 | 98 | 99 | class BaseFileInterface: 100 | def dump(self, path: Path): 101 | ... 102 | 103 | @classmethod 104 | def parse(cls, path: Path): 105 | ... 106 | ``` 107 | 108 | This is how you can implement this interface for Pydantic `BaseModel` class: 109 | 110 | ```python 111 | from impler import impl 112 | from pydantic import BaseModel 113 | from pathlib import Path 114 | 115 | 116 | @impl(BaseModel, as_parent=True) 117 | class ModelFileInterface(BaseFileInterface): 118 | def dump(self, path: Path): 119 | path.write_text(self.json()) 120 | 121 | @classmethod 122 | def parse(cls, path: Path): 123 | return cls.parse_file(path) 124 | 125 | ``` 126 | 127 | If `as_parent` parameter is `True` the implementation will be injected to the list of the target class parents. 128 | 129 | Then you can check if the class or object implements the interface: 130 | 131 | ```python 132 | print(issubclass(BaseModel, BaseFileInterfase)) 133 | # True 134 | 135 | print(issubclass(Point, BaseFileInterfase)) 136 | # True 137 | 138 | print(isinstance(point, BaseFileInterface)) 139 | # True 140 | ``` 141 | 142 | The whole api documentation could be found by the [link](https://github.com/roman-right/impler/blob/main/docs/api.md) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | config.cnf 2 | *.pyc 3 | *.iml 4 | */*.pytest* 5 | .rnd 6 | ### Python template 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | .hypothesis/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | .static_storage/ 62 | .media/ 63 | local_settings.py 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # pyenv 82 | .python-version 83 | 84 | # celery beat schedule file 85 | celerybeat-schedule 86 | 87 | # SageMath parsed files 88 | *.sage.py 89 | 90 | # Environments 91 | .env 92 | .venv 93 | env/ 94 | venv/ 95 | ENV/ 96 | env.bak/ 97 | venv.bak/ 98 | 99 | # Spyder project settings 100 | .spyderproject 101 | .spyproject 102 | 103 | # Rope project settings 104 | .ropeproject 105 | 106 | # mkdocs documentation 107 | /site 108 | 109 | # mypy 110 | .mypy_cache/ 111 | ### VirtualEnv template 112 | # Virtualenv 113 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 114 | .Python 115 | [Bb]in 116 | [Ii]nclude 117 | [Ll]ib 118 | [Ll]ib64 119 | [Ll]ocal 120 | pyvenv.cfg 121 | .venv 122 | pip-selfcheck.json 123 | ### JetBrains template 124 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 125 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 126 | 127 | # User-specific stuff: 128 | .idea/**/workspace.xml 129 | .idea/**/tasks.xml 130 | .idea/dictionaries 131 | 132 | # Sensitive or high-churn files: 133 | .idea/**/dataSources/ 134 | .idea/**/dataSources.ids 135 | .idea/**/dataSources.xml 136 | .idea/**/dataSources.local.xml 137 | .idea/**/sqlDataSources.xml 138 | .idea/**/dynamic.xml 139 | .idea/**/uiDesigner.xml 140 | 141 | # Gradle: 142 | .idea/**/gradle.xml 143 | .idea/**/libraries 144 | 145 | # CMake 146 | cmake-build-debug/ 147 | cmake-build-release/ 148 | 149 | # Mongo Explorer plugin: 150 | .idea/**/mongoSettings.xml 151 | 152 | ## File-based project format: 153 | *.iws 154 | 155 | ## Plugin-specific files: 156 | 157 | # IntelliJ 158 | out/ 159 | 160 | # mpeltonen/sbt-idea plugin 161 | .idea_modules/ 162 | 163 | # JIRA plugin 164 | atlassian-ide-plugin.xml 165 | 166 | # Cursive Clojure plugin 167 | .idea/replstate.xml 168 | 169 | # Crashlytics plugin (for Android Studio and IntelliJ) 170 | com_crashlytics_export_strings.xml 171 | crashlytics.properties 172 | crashlytics-build.properties 173 | fabric.properties 174 | 175 | .idea 176 | .pytest_cache 177 | docs/api 178 | docs/_rst 179 | tags 180 | 181 | tests/assets/tmp 182 | src/api_files/storage_dir 183 | docker-compose-aws.yml 184 | tilt_modules 185 | 186 | # Poetry stuff 187 | poetry.lock -------------------------------------------------------------------------------- /tests/test_impl_interface.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from impler import impl, impl_interface 4 | from impler.exceptions import ImplException 5 | 6 | pytestmark = pytest.mark.asyncio 7 | 8 | 9 | @pytest.fixture() 10 | def Cls(): 11 | class A: 12 | outer = 0 13 | 14 | def __init__(self): 15 | self.internal = 0 16 | 17 | def exists(self): 18 | return 0 19 | 20 | return A 21 | 22 | 23 | @pytest.fixture 24 | def Interface(): 25 | class Smth: 26 | value = 500 27 | _protected_val = 0 28 | 29 | def _protected_method(self): 30 | return 0 31 | 32 | def __magic_method__(self): 33 | return 0 34 | 35 | def get_100(self): 36 | return 100 37 | 38 | @classmethod 39 | def get_101(cls): 40 | return 101 41 | 42 | @staticmethod 43 | def get_102(): 44 | return 102 45 | 46 | async def get_103(self): 47 | return 103 48 | 49 | @classmethod 50 | async def get_104(cls): 51 | return 104 52 | 53 | @staticmethod 54 | async def get_105(): 55 | return 105 56 | 57 | def exists(self): 58 | return 100 59 | 60 | return Smth 61 | 62 | 63 | async def test_interface_as_parent(Cls, Interface): 64 | class Sample(Cls): 65 | ... 66 | 67 | s = Sample() 68 | 69 | @impl(Sample, as_parent=True) 70 | class New(Interface): 71 | ... 72 | 73 | assert isinstance(s, New) 74 | assert issubclass(Sample, New) 75 | assert s.get_100() == 100 76 | assert Sample.get_101() == 101 77 | assert Sample.get_102() == 102 78 | assert await s.get_103() == 103 79 | assert await Sample.get_104() == 104 80 | assert await Sample.get_105() == 105 81 | assert Sample.value == 500 82 | assert s.exists() == 0 83 | 84 | assert s._protected_val == 0 85 | assert s._protected_method() == 0 86 | assert s.__magic_method__() == 0 87 | 88 | 89 | async def test_interface_separated_function(Cls, Interface): 90 | class Sample(Cls): 91 | ... 92 | 93 | s = Sample() 94 | 95 | @impl_interface(Sample, as_parent=True) 96 | class New(Interface): 97 | ... 98 | 99 | assert isinstance(s, New) 100 | assert issubclass(Sample, New) 101 | assert s.get_100() == 100 102 | assert Sample.get_101() == 101 103 | assert Sample.get_102() == 102 104 | assert await s.get_103() == 103 105 | assert await Sample.get_104() == 104 106 | assert await Sample.get_105() == 105 107 | assert Sample.value == 500 108 | assert s.exists() == 0 109 | 110 | assert s._protected_val == 0 111 | assert s._protected_method() == 0 112 | assert s.__magic_method__() == 0 113 | 114 | 115 | async def test_interface_as_parent_override(Cls, Interface): 116 | class Sample(Cls): 117 | ... 118 | 119 | s = Sample() 120 | 121 | @impl(Sample, as_parent=True, override=True) 122 | class New(Interface): 123 | ... 124 | 125 | assert s.exists() == 100 126 | 127 | 128 | def test_interface_as_parent_inherited_from_object(Cls, Interface): 129 | with pytest.raises(ImplException): 130 | 131 | @impl(Cls, as_parent=True) 132 | class New(Interface): 133 | ... 134 | 135 | 136 | async def test_interface_not_as_parent(Cls, Interface): 137 | class Sample(Cls): 138 | ... 139 | 140 | s = Sample() 141 | 142 | @impl(Sample, as_parent=False) 143 | class New(Interface): 144 | ... 145 | 146 | assert not isinstance(s, New) 147 | assert not issubclass(Sample, New) 148 | assert s.get_100() == 100 149 | assert Sample.get_101() == 101 150 | assert Sample.get_102() == 102 151 | assert await s.get_103() == 103 152 | assert await Sample.get_104() == 104 153 | assert await Sample.get_105() == 105 154 | assert Sample.value == 500 155 | assert s.exists() == 0 156 | 157 | assert not hasattr(s, "_protected_val") 158 | assert not hasattr(s, "_protected_method") 159 | assert not hasattr(s, "__magic_method__") 160 | 161 | 162 | async def test_interface_not_as_parent_override(Cls, Interface): 163 | class Sample(Cls): 164 | ... 165 | 166 | s = Sample() 167 | 168 | @impl(Sample, as_parent=False, override=True) 169 | class New(Interface): 170 | ... 171 | 172 | assert s.exists() == 100 173 | 174 | 175 | async def test_interface_not_as_parent_copy_protected(Cls, Interface): 176 | class Sample(Cls): 177 | ... 178 | 179 | s = Sample() 180 | 181 | @impl(Sample, as_parent=False, copy_protected=True) 182 | class New(Interface): 183 | ... 184 | 185 | assert s._protected_val == 0 186 | assert s._protected_method() == 0 187 | 188 | 189 | async def test_interface_not_as_parent_copy_magic(Cls, Interface): 190 | class Sample(Cls): 191 | ... 192 | 193 | s = Sample() 194 | 195 | @impl(Sample, as_parent=False, copy_magic=True) 196 | class New(Interface): 197 | ... 198 | 199 | assert s.__magic_method__() == 0 200 | -------------------------------------------------------------------------------- /impler/main.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, unique 2 | from inspect import isclass 3 | from typing import Callable, Awaitable, Union, Type 4 | 5 | from impler.exceptions import ImplException 6 | 7 | 8 | @unique 9 | class _SubjectType(Enum): 10 | METHOD = 0 11 | CLASS_METHOD = 1 12 | STATIC_METHOD = 2 13 | INTERFACE = 3 14 | 15 | 16 | class impl: 17 | """ 18 | Decorator. 19 | 20 | Implementation of a method or of an interface for the classes. 21 | """ 22 | 23 | def __init__( 24 | self, 25 | target: Type, 26 | *, 27 | override: bool = False, 28 | as_parent: bool = False, 29 | copy_protected: bool = False, 30 | copy_magic: bool = False, 31 | as_classmethod: bool = False, 32 | as_staticmethod: bool = False, 33 | ): 34 | """ 35 | Init 36 | Args: 37 | For all: 38 | target: Type 39 | override: bool - should exist attributes and methods be overridden 40 | For interfaces: 41 | as_parent: bool - inject interface as a parent 42 | copy_protected: bool - copy protected fields *[Works only with inject_parent is Flase]* 43 | copy_magic: bool - copy magic methods and attributes *[Works only with inject_parent is Flase]* 44 | For methods: 45 | as_classmethod: bool - set method as a class method 46 | as_staticmethod: bool - set method as a static method 47 | """ 48 | self.target = target 49 | self.override = override 50 | 51 | self.as_parent = as_parent 52 | self.copy_protected = copy_protected 53 | self.copy_magic = copy_magic 54 | 55 | self.as_classmethod = as_classmethod 56 | self.as_staticmethod = as_staticmethod 57 | 58 | self.subject: Union[Callable, Awaitable, Type, None] = None 59 | self.subject_type = None 60 | 61 | def _validate_input(self): 62 | if self.subject_type != _SubjectType.INTERFACE: 63 | if self.as_parent or self.copy_protected or self.copy_magic: 64 | raise ImplException( 65 | "Incompatible input parameters for the method implementation" 66 | ) 67 | if self.as_classmethod and self.as_staticmethod: 68 | raise ImplException( 69 | "Implementation can not be and classmethod and static method the same time" 70 | ) 71 | if self.subject_type != _SubjectType.METHOD and ( 72 | self.as_classmethod or self.as_staticmethod 73 | ): 74 | raise ImplException( 75 | "Classmethod or staticmethod modifiers can not be applied to the method, which already is classmethod or staticmethod" 76 | ) 77 | else: 78 | if self.as_classmethod or self.as_staticmethod: 79 | raise ImplException( 80 | "Incompatible input parameters for the interface implementation" 81 | ) 82 | if self.as_parent and (self.copy_protected or self.copy_magic): 83 | raise ImplException( 84 | "Input parameters copy_protectd and copy_magic can not be used if interface was injected as a parent" 85 | ) 86 | 87 | def _detect_subject_type(self): 88 | if isclass(self.subject): 89 | self.subject_type = _SubjectType.INTERFACE 90 | elif isinstance(self.subject, classmethod): 91 | self.subject_type = _SubjectType.CLASS_METHOD 92 | elif isinstance(self.subject, staticmethod): 93 | self.subject_type = _SubjectType.STATIC_METHOD 94 | else: 95 | self.subject_type = _SubjectType.METHOD 96 | 97 | def _register_method(self): 98 | if self.subject_type in [ 99 | _SubjectType.STATIC_METHOD, 100 | _SubjectType.CLASS_METHOD, 101 | ]: 102 | name = self.subject.__func__.__name__ 103 | else: 104 | name = self.subject.__name__ 105 | if self.override or not hasattr(self.target, name): 106 | setattr(self.target, name, self.subject) 107 | 108 | def _inject_parent(self): 109 | if self.target.__bases__ == (object,): 110 | raise ImplException( 111 | "Parent injection to the object-based classes is impossible" 112 | ) 113 | else: 114 | if self.override: 115 | self.target.__bases__ = (self.subject,) + self.target.__bases__ 116 | else: 117 | self.target.__bases__ += (self.subject,) 118 | 119 | def _stick_attributes(self): 120 | for attr_name in dir(self.subject): 121 | is_magic = attr_name.startswith("__") and attr_name.endswith("__") 122 | is_private = ( 123 | False 124 | if is_magic 125 | else attr_name.startswith("__") 126 | and not attr_name.endswith("__") 127 | ) 128 | is_protected = ( 129 | False if is_magic or is_private else attr_name.startswith("_") 130 | ) 131 | is_present = hasattr(self.target, attr_name) 132 | 133 | if ( 134 | (not is_protected or self.copy_protected) 135 | and (not is_magic or self.copy_magic) 136 | and (not is_private) 137 | and (not is_present or self.override) 138 | ): 139 | setattr( 140 | self.target, attr_name, getattr(self.subject, attr_name) 141 | ) 142 | 143 | def _register_interface(self): 144 | if self.as_parent: 145 | self._inject_parent() 146 | else: 147 | self._stick_attributes() 148 | 149 | def _prepare_subject(self): 150 | if self.as_classmethod: 151 | self.subject = classmethod(self.subject) 152 | self.subject_type = _SubjectType.CLASS_METHOD 153 | elif self.as_staticmethod: 154 | self.subject = staticmethod(self.subject) 155 | self.subject_type = _SubjectType.STATIC_METHOD 156 | 157 | def __call__(self, subject: Union[Callable, Awaitable, Type]): 158 | self.subject = subject 159 | self._detect_subject_type() 160 | 161 | self._validate_input() 162 | self._prepare_subject() 163 | 164 | if self.subject_type == _SubjectType.INTERFACE: 165 | self._register_interface() 166 | else: 167 | self._register_method() 168 | 169 | return subject 170 | 171 | 172 | def impl_method( 173 | target: Type, 174 | *, 175 | override: bool = False, 176 | as_classmethod: bool = False, 177 | as_staticmethod: bool = False, 178 | ): 179 | """ 180 | Decorator. 181 | Set function as a method of the given class (regular, classmethod or staticmethod) 182 | Args: 183 | target: Type 184 | override: bool - should exist method be overridden 185 | as_classmethod: bool - set method as a class method 186 | as_staticmethod: bool - set method as a static method 187 | """ 188 | return impl( 189 | target=target, 190 | override=override, 191 | as_classmethod=as_classmethod, 192 | as_staticmethod=as_staticmethod, 193 | ) 194 | 195 | 196 | def impl_classmethod( 197 | target: Type, 198 | *, 199 | override: bool = False, 200 | ): 201 | """ 202 | Decorator. 203 | Set function as a classmethod of the given class 204 | Args: 205 | target: Type 206 | override: bool - should exist method be overridden 207 | """ 208 | return impl(target=target, override=override, as_classmethod=True) 209 | 210 | 211 | def impl_staticmethod( 212 | target: Type, 213 | *, 214 | override: bool = False, 215 | ): 216 | """ 217 | Decorator. 218 | Set function as a staticmethod of the given class 219 | Args: 220 | target: Type 221 | override: bool - should exist method be overridden 222 | """ 223 | return impl(target=target, override=override, as_staticmethod=True) 224 | 225 | 226 | def impl_interface( 227 | target: Type, 228 | *, 229 | override: bool = False, 230 | as_parent: bool = False, 231 | copy_protected: bool = False, 232 | copy_magic: bool = False, 233 | ): 234 | """ 235 | 236 | Args: 237 | target: Type 238 | override: bool - should exist attributes and methods be overridden 239 | as_parent: bool - inject interface as a parent 240 | copy_protected: bool - copy protected fields [Works only with inject_parent == Flase] 241 | copy_magic: bool - copy magic methods and attributes [Works only with inject_parent == Flase] 242 | """ 243 | return impl( 244 | target=target, 245 | override=override, 246 | as_parent=as_parent, 247 | copy_protected=copy_protected, 248 | copy_magic=copy_magic, 249 | ) 250 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Roman Korolev 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /assets/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 42 | 44 | 45 | 47 | image/svg+xml 48 | 50 | 51 | 52 | 53 | 54 | 59 | 62 | 66 | 70 | 74 | 78 | 82 | 86 | 90 | 94 | 98 | 102 | 106 | 110 | 114 | 118 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /assets/logo_sharp.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 22 | image/svg+xml 23 | 25 | 26 | 27 | 28 | 29 | 31 | 55 | 60 | 63 | 67 | 71 | 75 | 79 | 83 | 87 | 91 | 95 | 99 | 103 | 107 | 111 | 115 | 119 | 123 | 124 | 125 | 126 | --------------------------------------------------------------------------------