├── MANIFEST.in ├── setup.cfg ├── Makefile ├── tests ├── test_package_duplicate_2 │ ├── module.py │ └── __init__.py ├── test_package_duplicate_1 │ ├── module.py │ └── __init__.py ├── test_package_no_missing │ ├── module.py │ └── __init__.py ├── test_package │ ├── module_a.py │ ├── module_b.py │ └── __init__.py ├── test__init__.py ├── test_import_all.py ├── test_try_import.py └── test_lazy_imports.py ├── .github └── workflows │ ├── pypi_upload.yml │ ├── pytest.yml │ └── static_checks.yml ├── lazy_imports ├── __init__.py ├── try_import.py └── lazy_imports.py ├── pyproject.toml ├── .gitignore ├── setup.py ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include *.md 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 119 3 | statistics = True 4 | count = True 5 | show-source = True 6 | extend-ignore = E203 7 | 8 | [mypy] 9 | ignore_missing_imports = True 10 | 11 | [pydocstyle] 12 | convention = google 13 | add_ignore = D107,D105 14 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | src := lazy_imports 2 | test-src := tests 3 | other-src := setup.py 4 | 5 | check: 6 | pydocstyle --count $(src) $(test-src) $(other-src) 7 | black $(src) $(test-src) $(other-src) --check --diff 8 | flake8 $(src) $(test-src) $(other-src) 9 | isort $(src) $(test-src) $(other-src) --check --diff 10 | mdformat --check *.md 11 | mypy --install-types --non-interactive $(src) $(test-src) $(other-src) 12 | pylint $(src) 13 | 14 | format: 15 | black $(src) $(test-src) $(other-src) 16 | isort $(src) $(test-src) $(other-src) 17 | mdformat *.md 18 | 19 | test: 20 | pytest $(test-src) 21 | -------------------------------------------------------------------------------- /tests/test_package_duplicate_2/module.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test module.""" 16 | 17 | module = "mod" 18 | -------------------------------------------------------------------------------- /tests/test_package_duplicate_1/module.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test module.""" 16 | 17 | variable = "val" 18 | -------------------------------------------------------------------------------- /tests/test_package_no_missing/module.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test module.""" 16 | 17 | variable = "val" 18 | -------------------------------------------------------------------------------- /.github/workflows/pypi_upload.yml: -------------------------------------------------------------------------------- 1 | name: PyPI Upload 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: '3.x' 17 | 18 | - name: Install dependencies 19 | run: | 20 | python -m pip install --upgrade pip 21 | pip install -U setuptools wheel twine 22 | 23 | - name: Build and publish 24 | env: 25 | TWINE_USERNAME: __token__ 26 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 27 | run: | 28 | python setup.py sdist bdist_wheel 29 | twine upload dist/* 30 | -------------------------------------------------------------------------------- /tests/test_package/module_a.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | """Dummy test module.""" 16 | 17 | 18 | def func_of_module_a() -> str: 19 | """Dummy test function.""" 20 | return "func_of_module_a" 21 | -------------------------------------------------------------------------------- /tests/test__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May 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 | from packaging.version import Version 16 | 17 | from lazy_imports import __version__ 18 | 19 | 20 | def test__version__(): 21 | # if __version__ does not conform to PEP 440 InvalidVersion will be raised 22 | Version(__version__) 23 | -------------------------------------------------------------------------------- /tests/test_package/module_b.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | """Dummy test module.""" 16 | 17 | import some_module_that_is_not_available # noqa: F401 18 | 19 | 20 | def func_of_module_b() -> str: 21 | """Dummy test function.""" 22 | return "func_of_module_b" 23 | -------------------------------------------------------------------------------- /tests/test_import_all.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | from test_package_no_missing import * # noqa: F403 16 | 17 | from lazy_imports import __version__ as version 18 | 19 | 20 | def test_all() -> None: 21 | assert variable == "val" # noqa: F405 22 | assert __version__ == version # type: ignore # noqa: F405 23 | -------------------------------------------------------------------------------- /.github/workflows/pytest.yml: -------------------------------------------------------------------------------- 1 | name: pytest 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | schedule: 9 | # * is a special character in YAML so you have to quote this string 10 | # at 4 am 11 | - cron: '0 4 * * *' 12 | 13 | # Allows you to run this workflow manually from the Actions tab 14 | workflow_dispatch: 15 | 16 | jobs: 17 | build: 18 | runs-on: ubuntu-latest 19 | strategy: 20 | matrix: 21 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] 22 | 23 | steps: 24 | - uses: actions/checkout@v2 25 | 26 | - name: Set up Python ${{ matrix.python-version }} 27 | uses: actions/setup-python@v2 28 | with: 29 | python-version: ${{ matrix.python-version }} 30 | 31 | - name: Install dependencies 32 | run: | 33 | python -m pip install -U pip 34 | pip install --progress-bar off -U .[optional,testing] 35 | 36 | - name: Test with pytest 37 | run: pytest tests 38 | -------------------------------------------------------------------------------- /lazy_imports/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | """Lazy-Imports main package.""" 16 | 17 | from lazy_imports.lazy_imports import LazyImporter 18 | from lazy_imports.try_import import try_import 19 | 20 | 21 | # Versioning follows the Semantic Versioning Specification https://semver.org/ and 22 | # PEP 440 -- Version Identification and Dependency Specification: https://www.python.org/dev/peps/pep-0440/ # noqa: E501 23 | __version__ = "0.3.2rc1" 24 | 25 | __all__ = ["LazyImporter", "try_import", "__version__"] 26 | -------------------------------------------------------------------------------- /tests/test_package_duplicate_2/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test package.""" 16 | 17 | import sys 18 | from typing import TYPE_CHECKING 19 | 20 | from lazy_imports import LazyImporter 21 | 22 | 23 | _import_structure = { 24 | "module": ["module"], 25 | } 26 | 27 | # Direct imports for type-checking 28 | if TYPE_CHECKING: 29 | from .module import module # noqa: F401 30 | else: 31 | sys.modules[__name__] = LazyImporter( 32 | __name__, 33 | globals()["__file__"], 34 | _import_structure, 35 | ) 36 | -------------------------------------------------------------------------------- /tests/test_package_duplicate_1/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test package.""" 16 | 17 | import sys 18 | from typing import TYPE_CHECKING 19 | 20 | from lazy_imports import LazyImporter 21 | 22 | 23 | _import_structure = { 24 | "module": ["variable"], 25 | } 26 | 27 | # Direct imports for type-checking 28 | if TYPE_CHECKING: 29 | from .module import variable # noqa: F401 30 | else: 31 | sys.modules[__name__] = LazyImporter( 32 | __name__, 33 | globals()["__file__"], 34 | _import_structure, 35 | extra_objects={"variable": None}, 36 | ) 37 | -------------------------------------------------------------------------------- /tests/test_package_no_missing/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 Pascal Bachor 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 | """Dummy test package.""" 16 | 17 | import sys 18 | from typing import TYPE_CHECKING 19 | 20 | from lazy_imports import LazyImporter, __version__ 21 | 22 | 23 | _import_structure = { 24 | "module": ["variable"], 25 | } 26 | 27 | # Direct imports for type-checking 28 | if TYPE_CHECKING: 29 | from .module import variable # noqa: F401 30 | else: 31 | sys.modules[__name__] = LazyImporter( 32 | __name__, 33 | globals()["__file__"], 34 | _import_structure, 35 | extra_objects={"__version__": __version__}, 36 | ) 37 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 119 3 | target-version = ["py38"] 4 | 5 | [tool.isort] 6 | profile = "black" 7 | lines_after_imports = 2 8 | line_length = 119 9 | 10 | [tool.pylint."MASTER"] 11 | load-plugins = "pylintfileheader" 12 | file-header = "(# Copyright \\(c\\) \\d{4}.*\\n)*#\\n# Licensed under the Apache License, Version 2.0 \\(the \"License\"\\);\\n# you may not use this file except in compliance with the License.\\n# You may obtain a copy of the License at\\n#\\n# http://www.apache.org/licenses/LICENSE-2.0\\n#\\n# Unless required by applicable law or agreed to in writing, software\\n# distributed under the License is distributed on an \"AS IS\" BASIS,\\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n# See the License for the specific language governing permissions and\\n# limitations under the License.\\n\\n" 13 | 14 | [tool.pylint."MESSAGES CONTROL"] 15 | disable = [ 16 | "too-many-arguments", 17 | "invalid-name", 18 | "line-too-long", # checked by flake8 19 | "fixme", 20 | "too-many-instance-attributes", 21 | "protected-access", 22 | "broad-except", 23 | "too-few-public-methods", 24 | "arguments-differ", 25 | "consider-using-f-string", 26 | ] 27 | -------------------------------------------------------------------------------- /tests/test_package/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | """Dummy test package.""" 16 | 17 | import sys 18 | from typing import TYPE_CHECKING 19 | 20 | from lazy_imports import LazyImporter, __version__ 21 | 22 | 23 | _import_structure = { 24 | "module_a": ["func_of_module_a"], 25 | "module_b": ["func_of_module_b"], 26 | } 27 | 28 | # Direct imports for type-checking 29 | if TYPE_CHECKING: 30 | from .module_a import func_of_module_a # noqa: F401 31 | from .module_b import func_of_module_b # noqa: F401 32 | else: 33 | sys.modules[__name__] = LazyImporter( 34 | __name__, 35 | globals()["__file__"], 36 | _import_structure, 37 | extra_objects={"__version__": __version__}, 38 | ) 39 | -------------------------------------------------------------------------------- /.github/workflows/static_checks.yml: -------------------------------------------------------------------------------- 1 | name: Static Code Checks 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | schedule: 9 | # * is a special character in YAML so you have to quote this string 10 | # at 4 am 11 | - cron: '0 4 * * *' 12 | 13 | jobs: 14 | checks: 15 | env: 16 | src: "lazy_imports" 17 | other-src: "tests setup.py" 18 | 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - uses: actions/setup-python@v2 24 | with: 25 | python-version: 3.8 26 | 27 | - name: Install 28 | run: | 29 | python -m pip install -U pip 30 | pip install --progress-bar off -U .[checking,optional] 31 | 32 | - name: Check with pydocstyle 33 | run: pydocstyle --count ${{ env.src }} ${{ env.other-src }} 34 | 35 | - name: Check with black 36 | run: black ${{ env.src }} ${{ env.other-src }} --check --diff 37 | 38 | - name: Check with flake8 39 | run: flake8 ${{ env.src }} ${{ env.other-src }} 40 | 41 | - name: Check with isort 42 | run: isort ${{ env.src }} ${{ env.other-src }} --check --diff 43 | 44 | - name: Check with mdformat 45 | run: mdformat --check *.md 46 | 47 | - name: Check with mypy 48 | run: mypy --install-types --non-interactive ${{ env.src }} ${{ env.other-src }} 49 | 50 | - name: Check with pylint 51 | run: pylint ${{ env.src }} 52 | -------------------------------------------------------------------------------- /tests/test_try_import.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2018 Preferred Networks, Inc. 2 | # Copyright (c) 2021 Philip May 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import pytest 17 | 18 | from lazy_imports import try_import 19 | 20 | 21 | def test_try_import_is_successful() -> None: 22 | with try_import() as imports: 23 | pass 24 | assert imports.is_successful() 25 | imports.check() 26 | 27 | 28 | def test_try_import_is_successful_other_error() -> None: 29 | with pytest.raises(NotImplementedError): 30 | with try_import() as imports: 31 | raise NotImplementedError 32 | assert imports.is_successful() # No imports failed so `imports` is successful. 33 | imports.check() 34 | 35 | 36 | def test_try_import_not_successful() -> None: 37 | with try_import() as imports: 38 | raise ImportError 39 | assert not imports.is_successful() 40 | with pytest.raises(ImportError): 41 | imports.check() 42 | 43 | with try_import() as imports: 44 | raise SyntaxError 45 | assert not imports.is_successful() 46 | with pytest.raises(ImportError): 47 | imports.check() 48 | -------------------------------------------------------------------------------- /tests/test_lazy_imports.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | import pytest 16 | 17 | from lazy_imports import LazyImporter, __version__ 18 | 19 | 20 | def test_sinple_case() -> None: 21 | _import_structure = { 22 | "lazy_imports": ["LazyImporter"], 23 | } 24 | extra_objects = {"__version__": __version__} 25 | lazy_importer = LazyImporter( 26 | __name__, 27 | globals()["__file__"], 28 | _import_structure, 29 | extra_objects=extra_objects, 30 | ) 31 | 32 | assert lazy_importer._import_structure == _import_structure 33 | assert lazy_importer._objects == extra_objects 34 | 35 | lazy_importer_dir = dir(lazy_importer) 36 | 37 | assert "lazy_imports" in lazy_importer_dir 38 | assert "_import_structure" in lazy_importer_dir 39 | 40 | assert lazy_importer.__version__ == __version__ 41 | 42 | 43 | def test_imports() -> None: 44 | import test_package 45 | import test_package.module_a 46 | from test_package import func_of_module_a 47 | from test_package.module_a import func_of_module_a # noqa: F811 48 | 49 | assert func_of_module_a() == "func_of_module_a" 50 | 51 | with pytest.raises(ModuleNotFoundError): 52 | import test_package.module_b # noqa: F401 53 | 54 | with pytest.raises(ModuleNotFoundError): 55 | from test_package import func_of_module_b # noqa: F401 56 | 57 | 58 | def test_duplicate() -> None: 59 | with pytest.raises(ValueError): 60 | import test_package_duplicate_1 # noqa: F401 61 | 62 | with pytest.raises(ValueError): 63 | import test_package_duplicate_2 # noqa: F401 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # own settings 2 | .idea/ 3 | .vscode/ 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | .pybuilder/ 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | # For a library or package, you might want to ignore these files since the code is 91 | # intended to run in multiple environments; otherwise, check them in: 92 | # .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # pytype static type analyzer 139 | .pytype/ 140 | 141 | # Cython debug symbols 142 | cython_debug/ 143 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 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 | """Build script for setuptools.""" 16 | 17 | import os 18 | from typing import List 19 | 20 | import setuptools 21 | 22 | 23 | project_name = "lazy_imports" 24 | source_code = "https://github.com/telekom/lazy-imports" 25 | keywords = "import imports lazy" 26 | install_requires: List[str] = [] 27 | extras_require = { 28 | "checking": [ 29 | "black", 30 | "flake8", 31 | "isort", 32 | "mdformat", 33 | "pydocstyle", 34 | "mypy", 35 | "pylint", 36 | "pylintfileheader", 37 | ], 38 | "testing": ["pytest", "packaging"], 39 | } 40 | extras_require["all"] = list({package_name for value in extras_require.values() for package_name in value}) 41 | 42 | 43 | def get_version(): 44 | """Read version from ``__init__.py``.""" 45 | version_filepath = os.path.join(os.path.dirname(__file__), project_name, "__init__.py") 46 | with open(version_filepath) as f: 47 | for line in f: 48 | if line.startswith("__version__"): 49 | return line.strip().split()[-1][1:-1] 50 | assert False 51 | 52 | 53 | with open("README.md", "r", encoding="utf-8") as fh: 54 | long_description = fh.read() 55 | 56 | setuptools.setup( 57 | name=project_name, 58 | version=get_version(), 59 | maintainer="Philip May", 60 | author="Philip May", 61 | author_email="philip.may@t-systems.com", 62 | description="Tool to support lazy imports", 63 | long_description=long_description, 64 | long_description_content_type="text/markdown", 65 | url=source_code, 66 | project_urls={ 67 | "Bug Tracker": source_code + "/issues", 68 | "Source Code": source_code, 69 | "Contributing": source_code + "/blob/main/CONTRIBUTING.md", 70 | "Code of Conduct": source_code + "/blob/main/CODE_OF_CONDUCT.md", 71 | }, 72 | packages=setuptools.find_packages(), 73 | python_requires=">=3.8", 74 | install_requires=install_requires, 75 | extras_require=extras_require, 76 | keywords=keywords, 77 | classifiers=[ 78 | # "Development Status :: 3 - Alpha", 79 | "Development Status :: 4 - Beta", 80 | # "Development Status :: 5 - Production/Stable", 81 | "Intended Audience :: Developers", 82 | "License :: OSI Approved :: Apache Software License", 83 | "Programming Language :: Python :: 3", 84 | "Programming Language :: Python :: 3.8", 85 | "Programming Language :: Python :: 3.9", 86 | "Programming Language :: Python :: 3.10", 87 | "Programming Language :: Python :: 3.11", 88 | "Programming Language :: Python :: 3.12", 89 | "Programming Language :: Python :: 3 :: Only", 90 | "Topic :: Software Development", 91 | "Topic :: Software Development :: Libraries", 92 | "Topic :: Software Development :: Libraries :: Python Modules", 93 | "Operating System :: OS Independent", 94 | ], 95 | ) 96 | -------------------------------------------------------------------------------- /lazy_imports/try_import.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2018 Preferred Networks, Inc. 2 | # Copyright (c) 2021 Philip May 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | """Module for ``try_import()``. 17 | 18 | This is code taken from the `Optuna framework `__. 19 | Many thanks to Optuna for 20 | `your consent `__ 21 | to publish it as a standalone package. 22 | """ 23 | 24 | from types import TracebackType 25 | from typing import Optional, Tuple, Type 26 | 27 | 28 | class _DeferredImportExceptionContextManager: 29 | """Context manager to defer exceptions from imports. 30 | 31 | Catches :exc:`ImportError` and :exc:`SyntaxError`. 32 | If any exception is caught, this class raises an :exc:`ImportError` when being checked. 33 | 34 | """ 35 | 36 | def __init__(self) -> None: 37 | self._deferred: Optional[Tuple[Exception, str]] = None 38 | 39 | def __enter__(self) -> "_DeferredImportExceptionContextManager": 40 | """Enter the context manager. 41 | 42 | Returns: 43 | Itself. 44 | 45 | """ 46 | return self 47 | 48 | def __exit__( 49 | self, 50 | exc_type: Optional[Type[Exception]], 51 | exc_value: Optional[Exception], 52 | traceback: Optional[TracebackType], 53 | ) -> Optional[bool]: 54 | """Exit the context manager. 55 | 56 | Args: 57 | exc_type: 58 | Raised exception type. :obj:`None` if nothing is raised. 59 | exc_value: 60 | Raised exception object. :obj:`None` if nothing is raised. 61 | traceback: 62 | Associated traceback. :obj:`None` if nothing is raised. 63 | 64 | Returns: 65 | :obj:`None` if nothing is deferred, otherwise :obj:`True`. 66 | :obj:`True` will suppress any exceptions avoiding them from propagating. 67 | 68 | """ 69 | if isinstance(exc_value, (ImportError, SyntaxError)): 70 | if isinstance(exc_value, ImportError): 71 | message = ( 72 | "Tried to import '{}' but failed. Please make sure that the package is " 73 | "installed correctly to use this feature. Actual error: {}." 74 | ).format(exc_value.name, exc_value) 75 | elif isinstance(exc_value, SyntaxError): 76 | message = ( 77 | "Tried to import a package but failed due to a syntax error in {}. Please " 78 | "make sure that the Python version is correct to use this feature. Actual " 79 | "error: {}." 80 | ).format(exc_value.filename, exc_value) 81 | else: 82 | assert False 83 | 84 | self._deferred = (exc_value, message) 85 | return True 86 | return None 87 | 88 | def is_successful(self) -> bool: 89 | """Return whether the context manager has caught any exceptions. 90 | 91 | Returns: 92 | :obj:`True` if no exceptions are caught, :obj:`False` otherwise. 93 | 94 | """ 95 | return self._deferred is None 96 | 97 | def check(self) -> None: 98 | """Check whether the context manger has caught any exceptions. 99 | 100 | Raises: 101 | :exc:`ImportError`: 102 | If any exception was caught from the caught exception. 103 | 104 | """ 105 | if self._deferred is not None: 106 | exc_value, message = self._deferred 107 | raise ImportError(message) from exc_value 108 | 109 | 110 | def try_import() -> _DeferredImportExceptionContextManager: 111 | """Create a context manager that can wrap imports of optional packages to defer exceptions. 112 | 113 | Returns: 114 | Deferred import context manager. 115 | 116 | """ 117 | return _DeferredImportExceptionContextManager() 118 | -------------------------------------------------------------------------------- /lazy_imports/lazy_imports.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020, 2021 The HuggingFace Team 2 | # Copyright (c) 2021 Philip May, Deutsche Telekom AG 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | """Lazy-Imports module. 17 | 18 | This is code taken from the `HuggingFace team `__. 19 | Many thanks to HuggingFace for 20 | `your consent `__ 21 | to publish it as a standalone package. 22 | """ 23 | 24 | import importlib 25 | import os 26 | from dataclasses import dataclass 27 | from types import ModuleType 28 | from typing import Any, Dict, List, Union 29 | 30 | 31 | @dataclass 32 | class Submodule: 33 | """Submodule. 34 | 35 | Example: `from . import types`. 36 | """ 37 | 38 | def describe(self, key: str): 39 | """Describe the object.""" 40 | return f"submodule {key}" 41 | 42 | 43 | @dataclass 44 | class FromSubmodule: 45 | """Object exported from submodule. 46 | 47 | Example: `from .types import models, BaseModel`. 48 | """ 49 | 50 | submodule: str 51 | 52 | def describe(self, key: str): 53 | """Describe the object.""" 54 | return f"{key} from submodule {self.submodule}" 55 | 56 | 57 | @dataclass 58 | class Raw: 59 | """Raw object. 60 | 61 | Example: `__version__ = 0.0.1`. 62 | """ 63 | 64 | value: Any 65 | 66 | def describe(self, key: str): 67 | """Describe the object.""" 68 | return f"extra object {key} of type {type(self.value).__qualname__}" 69 | 70 | 71 | Export = Union[Submodule, FromSubmodule, Raw] 72 | 73 | 74 | class LazyImporter(ModuleType): 75 | """Do lazy imports.""" 76 | 77 | # Very heavily inspired by optuna.integration._IntegrationModule 78 | # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py 79 | def __init__( 80 | self, 81 | name: str, 82 | module_file: str, 83 | import_structure: Dict[str, List[str]], 84 | extra_objects: Union[Dict[str, Any], None] = None, 85 | ): 86 | super().__init__(name) 87 | self._exports: Dict[str, Export] = {} 88 | 89 | def safe_insert(key: str, value: Export): 90 | if (previous := self._exports.get(key)) is not None: 91 | raise ValueError(f"Duplicate symbol: {previous.describe(key)} and {value.describe(key)}") 92 | self._exports[key] = value 93 | 94 | for key, values in import_structure.items(): 95 | safe_insert(key, Submodule()) 96 | for value in values: 97 | safe_insert(value, FromSubmodule(submodule=key)) 98 | 99 | self._objects = {} if extra_objects is None else extra_objects 100 | for key, value in self._objects.items(): 101 | safe_insert(key, Raw(value=value)) 102 | 103 | # Needed for autocompletion in an IDE and wildcard imports (although those won't be lazy) 104 | self.__all__ = [*self._exports.keys()] 105 | self.__file__ = module_file 106 | self.__path__ = [os.path.dirname(module_file)] 107 | self._name = name 108 | self._import_structure = import_structure 109 | 110 | # Needed for autocompletion in an IDE 111 | def __dir__(self): 112 | return [*super().__dir__(), *self.__all__] 113 | 114 | def __getattr__(self, name: str) -> Any: 115 | target = self._exports.get(name) 116 | if target is None: 117 | raise AttributeError(f"module {self.__name__} has no attribute {name}") 118 | 119 | if isinstance(target, Submodule): 120 | value = self._get_module(name) 121 | elif isinstance(target, FromSubmodule): 122 | value = getattr(self._get_module(target.submodule), name) 123 | elif isinstance(target, Raw): 124 | value = target.value 125 | else: 126 | assert False 127 | 128 | setattr(self, name, value) 129 | return value 130 | 131 | def _get_module(self, module_name: str): 132 | return importlib.import_module("." + module_name, self.__name__) 133 | 134 | def __reduce__(self): 135 | return (self.__class__, (self._name, self.__file__, self._import_structure, self._objects)) 136 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [opensource@telekom.de](mailto:opensource@telekom.de). 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available 126 | at [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [faq]: https://www.contributor-covenant.org/faq 129 | [homepage]: https://www.contributor-covenant.org 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [translations]: https://www.contributor-covenant.org/translations 132 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 133 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Table of Contents 4 | 5 | - [Code of Conduct](#code-of-conduct) 6 | - [Reporting Bugs and Issues](#reporting-bugs-and-issues) 7 | - [Engaging in our Project](#engaging-in-our-project) 8 | - [Pull Request Checklist](#pull-request-checklist) 9 | - [Contributing Code](#contributing-code) 10 | - [Contributing Documentation](#contributing-documentation) 11 | - [Testing, linting and formatting](#testing-linting-and-formatting) 12 | - [Style Guidelines](#style-guidelines) 13 | - [Code Owners](#code-owners) 14 | 15 | ## Code of Conduct 16 | 17 | All members of the project community must abide by the 18 | [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). Only by respecting each other can we 19 | develop a productive and collaborative community. Instances of abusive, harassing, or otherwise 20 | unacceptable behavior may be reported by contacting 21 | [opensource@telekom.de](mailto:opensource@telekom.de) and/or a [code owner](#code-owners). 22 | 23 | We appreciate your courtesy of avoiding political questions here. Issues that are not related to 24 | the project itself will be closed by our community managers. 25 | 26 | ## Reporting Bugs and Issues 27 | 28 | - We use GitHub issues to track bugs and enhancement requests. 29 | - Please provide as much context as possible when you report a bug and open an issue. 30 | - Ensure the bug was not already reported by searching on GitHub under Issues. 31 | - The information you provide must be comprehensive enough to reproduce 32 | that issue for the assignee. 33 | 34 | ## Engaging in our Project 35 | 36 | - If you have a trivial fix or improvement, plese go ahead and create a pull request. 37 | - A general guide to pull requests is here: 38 | [About pull requests](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) 39 | - If you want you can address (with `@...`) a suitable [code owner](#code-owners) of this 40 | repository. 41 | - If you plan to do something more involved, please open an issue to start a discussion with us. 42 | - Relevant coding [style guidelines](#style-guidelines) are available in this document. 43 | - Should you wish to work on an issue, please claim it first by commenting 44 | on the GitHub issue that you want to work on. This is to prevent duplicated 45 | efforts from other contributors on the same issue. 46 | - If you have questions about one of the issues, please comment on them, 47 | and one of the maintainers will clarify. 48 | - We kindly ask you to follow the [Pull Request Checklist](#Pull-Request-Checklist) 49 | to ensure reviews can happen accordingly. 50 | 51 | ## Pull Request Checklist 52 | 53 | - Branch from the master branch and, if needed, rebase to the current master branch 54 | before submitting your pull request. You may be asked to rebase your changes if your 55 | branch doesn't merge cleanly with master. 56 | - Commits should be as small as possible while ensuring that each commit is correct 57 | independently (i.e., each commit should work and pass tests). 58 | - Test your changes as thoroughly as possible before you commit them. Preferably, 59 | automate your test by unit/integration tests. If tested manually, provide information 60 | about the test scope in the PR description (e.g. “Test passed: Upgrade version from 61 | 0.42 to 0.42.23.”). 62 | - To differentiate your PR from PRs ready to be merged and to avoid duplicated work, 63 | please prefix the title with \[WIP\]. 64 | - If your pull request is not getting reviewed, or you need a specific person to review it, 65 | you can @-reply a [code owner](#code-owners) asking for a review in the pull request. 66 | - Post review: 67 | - If a review requires you to change your commit(s), please test the changes again. 68 | - Amend the affected commit(s) and force push onto your branch. 69 | - Set respective comments in your GitHub review to resolved. 70 | - Create a general PR comment to notify the reviewers that your amendments are ready for 71 | another round of review. 72 | 73 | ## Contributing Code 74 | 75 | You are welcome to contribute code in order to fix a bug or to implement a new feature. 76 | The following rules governs code contributions: 77 | 78 | - Contributions must be licensed under the [license of this project](LICENSE). 79 | - Newly created files must be opened by the following file header and a 80 | blank line. 81 | 82 | ```python 83 | # Copyright (c) [, ] 84 | # 85 | # Licensed under the Apache License, Version 2.0 (the "License"); 86 | # you may not use this file except in compliance with the License. 87 | # You may obtain a copy of the License at 88 | # 89 | # http://www.apache.org/licenses/LICENSE-2.0 90 | # 91 | # Unless required by applicable law or agreed to in writing, software 92 | # distributed under the License is distributed on an "AS IS" BASIS, 93 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 94 | # See the License for the specific language governing permissions and 95 | # limitations under the License. 96 | 97 | ``` 98 | 99 | ## Contributing Documentation 100 | 101 | You are welcome to contribute documentation to the project. 102 | The following rule governs documentation contributions: 103 | 104 | - Contributions must be licensed under the [license of this project](LICENSE). 105 | - This is the same license as the code. 106 | 107 | ## Testing, linting and formatting 108 | 109 | To run unit tests locally, ensure that you have installed all relevant requirements. 110 | You will probably want to install it in "editable mode" if you are developing locally. 111 | 112 | ```bash 113 | $ pip install -e .[optional,testing,checking] 114 | ``` 115 | 116 | Unit tests can then be run as follows: 117 | 118 | ```bash 119 | $ pytest -v tests 120 | ``` 121 | 122 | To check for linting errors use make (not available on Windows): 123 | 124 | ```bash 125 | $ make check 126 | ``` 127 | 128 | To format the code use make (not available on Windows): 129 | 130 | ```bash 131 | $ make format 132 | ``` 133 | 134 | ## Style Guidelines 135 | 136 | - The code must be compatible with Python 3.8 and higher. 137 | - Max line length is 119 138 | - Docstrings 139 | - Use the [Google docstring format](https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings). 140 | This is integrated with [Sphinx](https://www.sphinx-doc.org/) using the 141 | [napoleon extension](https://sphinxcontrib-napoleon.readthedocs.io/). 142 | - Versioning follows the [Semantic Versioning Specification](https://semver.org/) and 143 | [PEP 440 -- Version Identification and Dependency Specification](https://www.python.org/dev/peps/pep-0440/). 144 | 145 | ## Code Owners 146 | 147 | [@PhilipMay](https://github.com/PhilipMay) - code, general documentation, GitHub actions, 148 | everything else 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lazy-Imports 2 | 3 | > [!CAUTION] 4 | > This repository is deprecated and should no longer be used.\ 5 | > It is replaced by the friendly fork [lazy-imports](https://github.com/bachorp/lazy-imports) from [Pascal Bachor](https://github.com/bachorp). 6 | 7 | [![Apache-2.0 License](https://img.shields.io/github/license/telekom/lazy-imports)](https://github.com/telekom/lazy-imports/blob/main/LICENSE) 8 | [![Contributor Covenant](https://img.shields.io/badge/Code%20of%20Conduct-Contributor%20Covenant-ff69b4.svg)](https://github.com/telekom/lazy-imports/blob/main/CODE_OF_CONDUCT.md) 9 | [![Python Version](https://img.shields.io/pypi/pyversions/lazy-imports)](https://www.python.org) 10 | [![pypi](https://img.shields.io/pypi/v/lazy-imports.svg)](https://pypi.python.org/pypi/lazy-imports) 11 |
12 | [![pytest](https://github.com/telekom/lazy-imports/actions/workflows/pytest.yml/badge.svg)](https://github.com/telekom/lazy-imports/actions/workflows/pytest.yml) 13 | [![Static Code Checks](https://github.com/telekom/lazy-imports/actions/workflows/static_checks.yml/badge.svg)](https://github.com/telekom/lazy-imports/actions/workflows/static_checks.yml) 14 | [![GitHub issues](https://img.shields.io/github/issues-raw/telekom/lazy-imports)](https://github.com/telekom/lazy-imports/issues) 15 | 16 | This is a Python tool to support lazy imports. 17 | Likewise, the actual initialization of the module does not occur until usage time 18 | to postpone `ModuleNotFoundError`s to the time of the actual usage of the module. 19 | This is useful when using various optional dependencies which might not all be 20 | installed or which have high load times and/or ressource consumption. 21 | 22 | ## Table of Contents 23 | 24 | - [Maintainers](#maintainers) 25 | - [Installation](#installation) 26 | - [Usage & Example for LazyImporter](#usage--example-for-lazyimporter) 27 | - [Usage & Example for try_import](#usage--example-for-try_import) 28 | - [Support and Feedback](#support-and-feedback) 29 | - [Reporting Security Vulnerabilities](#reporting-security-vulnerabilities) 30 | - [Contribution](#contribution) 31 | - [Code of Conduct](#code-of-conduct) 32 | - [Licensing](#licensing) 33 | 34 | ## Maintainers 35 | 36 | This project is maintained by a team of [Deutsche Telekom AG](https://www.telekom.com/). 37 | It is based on 38 | [`_LazyModule`](https://github.com/huggingface/transformers/blob/e218249b02465ec8b6029f201f2503b9e3b61feb/src/transformers/file_utils.py#L1945) 39 | from [HuggingFace](https://huggingface.co/) and 40 | [`try_import()`](https://github.com/optuna/optuna/blob/1f92d496b0c4656645384e31539e4ee74992ff55/optuna/_imports.py#L89) 41 | from the [Optuna framework](https://optuna.readthedocs.io/). 42 | Many thanks to HuggingFace for 43 | [your consent](https://github.com/huggingface/transformers/issues/12861#issuecomment-886712209) 44 | and to Optuna for 45 | [your consent](https://github.com/optuna/optuna/issues/2776#issuecomment-874614137) 46 | to publish it as a standalone package 🤗 ♥. 47 | 48 | ## Installation 49 | 50 | Lazy-Imports is available at [the Python Package Index (PyPI)](https://pypi.org/project/lazy-imports/). 51 | It can be installed with pip: 52 | 53 | ```bash 54 | $ pip install lazy-imports 55 | ``` 56 | 57 | ## Usage & Example for LazyImporter 58 | 59 | A good and easy to understand example of how to use Lazy-Imports can be found in the 60 | [`__init__.py` file of the HPOflow package](https://github.com/telekom/HPOflow/blob/1b26f3b86cad607dd89a31fa9135256d956948cb/hpoflow/__init__.py). 61 | It is printed here: 62 | 63 | ```python 64 | import sys 65 | from typing import TYPE_CHECKING 66 | 67 | from lazy_imports import LazyImporter 68 | 69 | from hpoflow.version import __version__ 70 | 71 | 72 | _import_structure = { 73 | "mlflow": [ 74 | "normalize_mlflow_entry_name", 75 | "normalize_mlflow_entry_names_in_dict", 76 | "check_repo_is_dirty", 77 | ], 78 | "optuna": ["SignificanceRepeatedTrainingPruner"], 79 | "optuna_mlflow": ["OptunaMLflow"], 80 | "optuna_transformers": ["OptunaMLflowCallback"], 81 | "utils": ["func_no_exception_caller"], 82 | } 83 | 84 | # Direct imports for type-checking 85 | if TYPE_CHECKING: 86 | from hpoflow.mlflow import ( # noqa: F401 87 | check_repo_is_dirty, 88 | normalize_mlflow_entry_name, 89 | normalize_mlflow_entry_names_in_dict, 90 | ) 91 | from hpoflow.optuna import SignificanceRepeatedTrainingPruner # noqa: F401 92 | from hpoflow.optuna_mlflow import OptunaMLflow # noqa: F401 93 | from hpoflow.optuna_transformers import OptunaMLflowCallback # noqa: F401 94 | from hpoflow.utils import func_no_exception_caller # noqa: F401 95 | else: 96 | sys.modules[__name__] = LazyImporter( 97 | __name__, 98 | globals()["__file__"], 99 | _import_structure, 100 | extra_objects={"__version__": __version__}, 101 | ) 102 | ``` 103 | 104 | ## Usage & Example for try_import 105 | 106 | `try_import` is a context manager that can wrap imports of optional packages to defer 107 | exceptions. This way you don't have to import the packages every time you call a function, 108 | but you can still import the package at the top of your module. The context manager 109 | defers the exceptions until you actually need to use the package. 110 | You can see an example below: 111 | 112 | ```python 113 | from lazy_imports import try_import 114 | 115 | with try_import() as optional_package_import: # use try_import as a context manager 116 | import optional_package # optional package that might not be installed 117 | 118 | # other non optional functions here 119 | 120 | def optional_function(): # optional function that uses the optional package 121 | optional_package_import.check() # check if the import was ok or raise a meaningful exception 122 | 123 | optional_package.some_external_function() # use the optional package here 124 | ``` 125 | 126 | ## Support and Feedback 127 | 128 | The following channels are available for discussions, feedback, and support requests: 129 | 130 | - [open an issue in our GitHub repository](https://github.com/telekom/lazy-imports/issues/new/choose) 131 | - [send an e-mail to our open source team](mailto:opensource@telekom.de) 132 | 133 | ## Reporting Security Vulnerabilities 134 | 135 | This project is built with security and data privacy in mind to ensure your data is safe. 136 | We are grateful for security researchers and users reporting a vulnerability to us, first. 137 | To ensure that your request is handled in a timely manner and non-disclosure of vulnerabilities 138 | can be assured, please follow the below guideline. 139 | 140 | **Please do not report security vulnerabilities directly on GitHub. 141 | GitHub Issues can be publicly seen and therefore would result in a direct disclosure.** 142 | 143 | Please address questions about data privacy, security concepts, 144 | and other media requests to the [opensource@telekom.de](mailto:opensource@telekom.de) mailbox. 145 | 146 | ## Contribution 147 | 148 | Our commitment to open source means that we are enabling - in fact encouraging - all interested 149 | parties to contribute and become part of our developer community. 150 | 151 | Contribution and feedback is encouraged and always welcome. For more information about how to 152 | contribute, as well as additional contribution information, see our 153 | [Contribution Guidelines](https://github.com/telekom/lazy-imports/blob/main/CONTRIBUTING.md). 154 | 155 | ## Code of Conduct 156 | 157 | This project has adopted the [Contributor Covenant](https://www.contributor-covenant.org/) 158 | as our code of conduct. Please see the details in our 159 | [Contributor Covenant Code of Conduct](https://github.com/telekom/lazy-imports/blob/main/CODE_OF_CONDUCT.md). 160 | All contributors must abide by the code of conduct. 161 | 162 | ## Licensing 163 | 164 | Copyright (c) 2021 [Philip May](https://may.la/), [Deutsche Telekom AG](https://www.telekom.com/)
165 | Copyright (c) 2020, 2021 [The HuggingFace Team](https://huggingface.co/)
166 | Copyright (c) 2018 Preferred Networks, Inc. 167 | 168 | Licensed under the [Apache License, Version 2.0](https://github.com/telekom/lazy-imports/blob/main/LICENSE) (the "License"); 169 | you may not use this file except in compliance with the License. 170 | You may obtain a copy of the License at 171 | 172 | [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 173 | 174 | Unless required by applicable law or agreed to in writing, software 175 | distributed under the License is distributed on an "AS IS" BASIS, 176 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 177 | See the License for the specific language governing permissions and 178 | limitations under the License. 179 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | --------------------------------------------------------------------------------