diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..c9162b9
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,12 @@
+root = true
+
+[*]
+charset = utf-8
+indent_style = tab
+indent_size = 4
+insert_final_newline = true
+end_of_line = lf
+
+[*.{yml,yaml}]
+indent_style = space
+indent_size = 2
diff --git a/.github/.templateMarker b/.github/.templateMarker
new file mode 100644
index 0000000..5e3a3e0
--- /dev/null
+++ b/.github/.templateMarker
@@ -0,0 +1 @@
+KOLANICH/python_project_boilerplate.py
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..89ff339
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,8 @@
+version: 2
+updates:
+ - package-ecosystem: "pip"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ allow:
+ - dependency-type: "all"
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
new file mode 100644
index 0000000..7fe33b3
--- /dev/null
+++ b/.github/workflows/CI.yml
@@ -0,0 +1,15 @@
+name: CI
+on:
+ push:
+ branches: [master]
+ pull_request:
+ branches: [master]
+
+jobs:
+ build:
+ runs-on: ubuntu-22.04
+ steps:
+ - name: typical python workflow
+ uses: KOLANICH-GHActions/typical-python-workflow@master
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b89f11f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+__pycache__
+*.py[co]
+/*.egg-info
+/build
+/dist
+/.eggs
+.hypothesis
+rspec.xml
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644
index 0000000..522e4b3
--- /dev/null
+++ b/.gitlab-ci.yml
@@ -0,0 +1,63 @@
+image: pypy:latest
+#image: registry.gitlab.com/kolanich/fixed_python:latest
+
+build:
+ tags:
+ - shared
+ stage: build
+ variables:
+ GIT_DEPTH: "1"
+ PYTHONUSERBASE: ${CI_PROJECT_DIR}/python_user_packages
+
+ before_script:
+ - export PATH="$PATH:$PYTHONUSERBASE/bin" # don't move into `variables`
+ - pip3 install --pre --upgrade --user setuptools
+ - pip3 install --pre --upgrade --user setuptools_scm
+ - pip3 install --pre --upgrade --user git+https://github.com/pypa/pip.git git+https://github.com/pypa/wheel.git
+ - pip3 install --pre --upgrade --user git+https://github.com/KOLANICH/sideBySideDiff.py.git
+ - pip3 install --pre --upgrade --user git+https://github.com/pytest-dev/pytest.git git+https://github.com/pytest-dev/pytest-forked.git
+ - pip3 install --pre --user coverage git+https://github.com/coveralls-clients/coveralls-python.git@eba54e4d19e40e3907e5fd516f68e8b4dc9e5a31 git+https://github.com/codecov/codecov-python.git@0743daa83647f12ff31b84d07113d2c24c27b924
+ cache:
+ paths:
+ - /usr/local/site-packages
+ - /usr/local/lib/python*/site-packages
+
+ script:
+ - pypy3 setup.py bdist_wheel
+ - pip3 install --user --upgrade ./dist/*.whl
+ - cd ./tests
+ - coverage run -a --source=lazily --branch -m pytest --junitxml=./rspec.xml --forked ./test*.py
+ - coverage report -m || true
+ - coverage xml
+ - cd ..
+ - mkdir wheels
+ - mv ./dist/*.whl ./wheels/lazily-0.CI-py3-none-any.whl
+
+ artifacts:
+ paths:
+ - wheels
+ - $PYTHONUSERBASE
+ reports:
+ junit: ./rspec.xml
+ cobertura: ./coverage.xml
+
+checks:
+ stage: test
+ tags:
+ - shared
+ image: docker:latest
+ variables:
+ DOCKER_DRIVER: overlay2
+ allow_failure: true
+ services:
+ - docker:dind
+ script:
+ - docker run --env SAST_CONFIDENCE_LEVEL=5 --volume "$PWD:/code" --volume /var/run/docker.sock:/var/run/docker.sock "registry.gitlab.com/gitlab-org/security-products/sast:latest" /app/bin/run /code
+ #- docker run --env SOURCE_CODE="$PWD" --env CODECLIMATE_VERSION="latest" --volume "$PWD":/code --volume /var/run/docker.sock:/var/run/docker.sock "registry.gitlab.com/gitlab-org/security-products/codequality:latest" /code
+ #- docker run --env DEP_SCAN_DISABLE_REMOTE_CHECKS="${DEP_SCAN_DISABLE_REMOTE_CHECKS:-false}" --volume "$PWD:/code" --volume /var/run/docker.sock:/var/run/docker.sock "registry.gitlab.com/gitlab-org/security-products/dependency-scanning:latest" /code
+
+ artifacts:
+ reports:
+ #codequality: gl-code-quality-report.json
+ sast: gl-sast-report.json
+ #dependency_scanning: gl-dependency-scanning-report.json
diff --git a/Code_Of_Conduct.md b/Code_Of_Conduct.md
new file mode 100644
index 0000000..2b781c7
--- /dev/null
+++ b/Code_Of_Conduct.md
@@ -0,0 +1 @@
+No codes of conduct!
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..20f0fa8
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,4 @@
+include UNLICENSE
+include *.md
+include tests
+include .editorconfig
diff --git a/ReadMe.md b/ReadMe.md
new file mode 100644
index 0000000..5210922
--- /dev/null
+++ b/ReadMe.md
@@ -0,0 +1,41 @@
+lazily.py [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/)
+===============
+~~[![GitLab Build Status](https://gitlab.com/KOLANICH/lazily.py/badges/master/pipeline.svg)](https://gitlab.com/KOLANICH/lazily.py/pipelines/master/latest)~~
+[![PyPi Status](https://img.shields.io/pypi/v/lazily.py.svg)](https://pypi.python.org/pypi/lazily.py)
+~~![GitLab Coverage](https://gitlab.com/KOLANICH/lazily.py/badges/master/coverage.svg)~~
+[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH/lazily.py.svg)](https://libraries.io/github/KOLANICH/lazily.py)
+[![Code style: antiflash](https://img.shields.io/badge/code%20style-antiflash-FFF.svg)](https://codeberg.org/KOLANICH-tools/antiflash.py)
+
+Imports lazily. Supports hooks.
+
+Useful when some long loading packages are optional to use by your app, so you don't want to spend time on loading them every time. The arguments are the same as in [`importlib.import_module`](https://docs.python.org/3/library/importlib.html#importlib.import_module).
+
+Requirements
+------------
+* [`lazy_object_proxy`](https://github.com/ionelmc/python-lazy-object-proxy) [![PyPi Status](https://img.shields.io/pypi/v/lazy-object-proxy.svg)](https://pypi.python.org/pypi/lazy-object-proxy)
+[![Libraries.io Status](https://img.shields.io/librariesio/github/ionelmc/python-lazy-object-proxy.svg)](https://libraries.io/github/ionelmc/python-lazy-object-proxy) It hooks into cpython and can catch more kinds of actual using of the object than any pure python implementation.
+
+
+```python
+import freeLunch # ModuleNotFoundError: No module named 'freeLunch'
+```
+
+```python
+from lazily import freeLunch
+
+freeLunch.consume() # ModuleNotFoundError: No module named 'freeLunch'
+```
+
+There is a hooks mechanics, but it is a bit broken, don't use for now:
+
+```python
+import lazily
+def bar():
+ raise ImportError("There ain't no such thing as a free lunch.")
+lazily.hooks["freeLunch"] = bar
+freeLunch = lazily.lazily("freeLunch")
+
+freeLunch.consume() # ImportError: There ain't no such thing as a free lunch.
+```
+
+Obviously, `*` in `fromlist` is UB, as it relies on `__all__`, so `_bootstrap.py` in CPython impl tries to read it.
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to
diff --git a/lazily/__init__.py b/lazily/__init__.py
new file mode 100644
index 0000000..075fa0d
--- /dev/null
+++ b/lazily/__init__.py
@@ -0,0 +1,233 @@
+__all__ = ("lazyImport", "Hook")
+import sys
+import traceback
+import functools
+import importlib
+import importlib.abc
+from importlib._bootstrap import _find_spec
+from importlib._bootstrap_external import PathFinder
+import inspect
+import lazy_object_proxy
+
+
+_lazilyGlobals = globals()
+
+
+
+def ProxyWithWorkaround_(factory, **_delayed):
+ class ProxyWithWorkaround(lazy_object_proxy.Proxy):
+ """A lazy_object_proxy class working around some `importlib._bootstrap` shit triggering importing of packages even if it was not requested"""
+
+ def __getattr__(self, key):
+ #print("__getattr__", _delayed is not None, key)
+ spr = super()
+ if _delayed is not None:
+ if key in _delayed:
+ return _delayed[key]
+ else:
+ s = traceback.extract_stack()[-2]
+ #print(s.name, s.name=="_handle_fromlist")
+ #print(s.filename, s.filename=="")
+
+ if s.name == "_handle_fromlist":
+ _bootstrapShitTriggers = (s.filename == "") #_bootstrap shit triggering importing of packages even if it was not requested
+ try:
+ # assertions are removed via optimization, this check is needed for interpreter with patched FrozedTable (useful for debugging this shit)
+ assert s.filename.endswith("importlib\\_bootstrap_external.py") # Windows
+ assert s.filename.endswith("importlib/_bootstrap_external.py") # Linux
+ except :
+ _bootstrapShitTriggers = True
+
+ if _bootstrapShitTriggers :
+ return ProxyWithWorkaround_(lambda: spr.__getattr__(key))
+ else:
+ return lazy_object_proxy.Proxy(lambda: spr.__getattr__(key))
+ #print("key", key)
+ #return spr.__getattr__(key)
+ else:
+ return lazy_object_proxy.Proxy(lambda: spr.__getattr__(key))
+
+ def __setattr__(self, key, value):
+ if _delayed is not None:
+ _delayed[key] = value
+ else:
+ super().__setattr__(key, value)
+
+ @functools.wraps(factory)
+ def factory1(*args, **kwargs):
+ nonlocal _delayed
+ #from traceback import print_stack
+ #print_stack()
+ res = factory(*args, **kwargs)
+ #if _delayed is not None:
+ # for k, v in _delayed.items():
+ # setattr(res, k, v)
+ # _delayed = None
+ return res
+ res = ProxyWithWorkaround(factory1)
+ return res
+
+
+ProxyWithWorkaround = ProxyWithWorkaround_
+
+
+class Hook:
+ __slots__ = ("moduleImporter", "modulePostProcessor", "propertyPostProcessor")
+
+ def __init__(self, moduleImporter=None, modulePostProcessor=None, propertyPostProcessor=None):
+ self.moduleImporter = moduleImporter
+ self.modulePostProcessor = modulePostProcessor
+ self.propertyPostProcessor = propertyPostProcessor
+
+ def __iadd__(self, other):
+ for k in __class__.__slots__:
+ v = getattr(other, k)
+ if v:
+ setattr(self, k, v)
+ return self
+
+
+def neutralHook(importedModule):
+ return importedModule
+
+
+def postProcessPandas(pandas):
+ if "tqdm" in sys.modules:
+ from tqdm.auto import tqdm
+
+ tqdm.pandas()
+ return pandas
+
+
+hooks = {"pandas": Hook(modulePostProcessor=postProcessPandas)}
+
+
+def getOuterFrame():
+ frame = inspect.currentframe()
+ stack = traceback.extract_stack()
+ for frameSumm in reversed(stack):
+ if frameSumm.filename != __file__:
+ break
+ frame = frame.f_back
+ return (frame, frameSumm)
+
+
+def genImporterFunc(name, package=None, fromlist=(), *args, **kwargs):
+ h = Hook(moduleImporter=None, modulePostProcessor=neutralHook, propertyPostProcessor=neutralHook)
+ if name in hooks:
+ h += hooks[name]
+
+ if not package and name[0] == ".":
+ (frame, frameSumm) = getOuterFrame()
+ package = frame.f_globals["__package__"]
+
+ if h.moduleImporter is None:
+ h.moduleImporter = functools.partial(importlib.import_module, name, package, *args, **kwargs)
+
+ def readyModuleImporter():
+ prepName = LazyImporter.marker + name #dot is included into marker
+ #traceback.print_stack()
+ #print(groups.Fore.lightgreenEx("prepName")+' "' + groups.Fore.lightcyanEx(prepName) + '"' + " in sys.modules :", prepName in sys.modules)
+ #print(groups.Fore.lightgreenEx("name")+' "' + groups.Fore.lightcyanEx(name) + '"' + " in sys.modules :", name in sys.modules)
+
+ return h.modulePostProcessor(h.moduleImporter())
+
+ if fromlist:
+ def readyPropertyImporter():
+ module = readyModuleImporter()
+ res = []
+ for nm in fromlist:
+ res.append(h.propertyPostProcessor(getattr(module, nm)))
+ if len(res) == 1:
+ return res[0]
+ else:
+ return tuple(res)
+ #print("func is readyPropertyImporter", readyPropertyImporter)
+ return readyPropertyImporter
+ else:
+ #print("func is readyModuleImporter", readyModuleImporter)
+ return readyModuleImporter
+
+
+def lazyImport(name, package=None, fromlist=(), *args, **kwargs):
+ """Imports lazily"""
+ return ProxyWithWorkaround(genImporterFunc(name, package, fromlist, *args, **kwargs))
+
+#from RichConsole import groups
+
+class LazyImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader):
+ __slots__ = ("failImmediately",)
+ marker = __name__ + "."
+
+ def __init__(self, *args, failImmediately=False, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.failImmediately = failImmediately
+
+ def find_spec(self, fullName, path, target=None, *args, **kwargs):
+ #print(groups.Fore.lightredEx("find_spec")+" "+groups.Fore.lightcyanEx(fullName), path, target, args, kwargs)
+ if not fullName.startswith(__class__.marker):
+ #import traceback
+ #traceback.print_stack()
+ return None
+ else:
+ trueName = fullName[len(__class__.marker):]
+ #print("trueName", trueName)
+ trueNameComponents = trueName.split(".")
+ #print(trueNameComponents)
+
+ try:
+ if len(trueNameComponents) == 1:
+ origSpec = importlib.util.find_spec(trueName)
+ else:
+ origSpec = _find_spec(trueName, sys.modules[__class__.marker+".".join(trueNameComponents[:-1])].__path__) # should not trigger loading, since worked aroung. Workaround is needed not only here, so we cannot remove it
+ #origSpec = None # if it is a submodule we don't search for a spec, it triggers executing
+ except:
+ if not self.failImmediately:
+ origSpec = None
+ else:
+ raise
+
+ if origSpec:
+ spec = importlib.machinery.ModuleSpec(
+ name=fullName,
+ loader=self,
+ origin=origSpec.origin,
+ loader_state=None,
+ )
+ spec.submodule_search_locations=origSpec.submodule_search_locations
+ else:
+ if self.failImmediately:
+ raise ImportError("Could not import `"+trueName+"`: `origSpec` is None, which may mean there is no such a module")
+ else:
+ spec = importlib.machinery.ModuleSpec(
+ name=fullName,
+ loader=self,
+ )
+
+ spec.has_location = False
+ spec.trueName = trueName
+ return spec
+
+ def create_module(self, spec, *args, **kwargs):
+ #print(groups.Fore.lightredEx("create_module") + ' "' + groups.Fore.lightcyanEx(spec.name) + '"' + " in sys.modules :", spec.name in sys.modules)
+ return None
+
+ def exec_module(self, module, *args, **kwargs):
+ trueName = module.__spec__.name[len(__class__.marker):]
+ #print(groups.Fore.lightredEx("exec_module")+' "' +groups.Fore.lightcyanEx(module.__spec__.name) + '"' + " in sys.modules :", module.__spec__.name in sys.modules, '"' + groups.Fore.lightcyanEx(trueName) + '"' + " in sys.modules :", trueName in sys.modules)
+ #print("module.__spec__.origin", module.__spec__.submodule_search_locations)
+ mod = ProxyWithWorkaround(genImporterFunc(trueName), __spec__=module.__spec__, __file__=None, __path__=module.__spec__.submodule_search_locations)
+ #mod = ProxyWithWorkaround(genImporterFunc(trueName), __spec__=module.__spec__, __file__=module.__spec__.submodule_search_locations)
+ #mod = __import__(trueName)
+ #print("exec_module", trueName, "mod", "(", mod, ")")
+ sys.modules[module.__spec__.name] = mod
+ return mod
+
+
+def findPathFinderIndex():
+ for i, v in enumerate(sys.meta_path):
+ if v is PathFinder:
+ return i
+
+_importer = LazyImporter()
+sys.meta_path.insert(findPathFinderIndex(), _importer)
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..9c59ae9
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,39 @@
+[build-system]
+requires = ["setuptools>=61.2.0", "wheel", "setuptools_scm[toml]>=3.4.3",]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "lazily"
+authors = [{name = "KOLANICH"}]
+description = "Imports other modules lazily."
+readme = "ReadMe.md"
+keywords = ["import", "lazy"]
+license = {text = "Unlicense"}
+classifiers = [
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Development Status :: 4 - Beta",
+ "Environment :: Other Environment",
+ "Intended Audience :: Developers",
+ "License :: Public Domain",
+ "Operating System :: OS Independent",
+]
+urls = {Homepage = "https://codeberg.org/KOLANICH-libs/lazily.py"}
+requires-python = ">=3.4"
+dependencies = ["lazy_object_proxy"]
+dynamic = ["version"]
+
+[project.optional-dependencies]
+tests = [
+ "sideBySideDiff", # @ git+https://codeberg.org/KOLANICH-libs/sideBySideDiff.py.git
+]
+
+[tool.setuptools]
+zip-safe = true
+packages = ["lazily"]
+
+[tool.setuptools_scm]
+
+[tool.pytest.ini_options]
+addopts = "--forked"
+testpaths = ["tests"]
diff --git a/tests/.hypothesis/unicode_data/13.0.0/charmap.json.gz b/tests/.hypothesis/unicode_data/13.0.0/charmap.json.gz
new file mode 100644
index 0000000..074e3bc
Binary files /dev/null and b/tests/.hypothesis/unicode_data/13.0.0/charmap.json.gz differ
diff --git a/tests/ImportTimeline.py b/tests/ImportTimeline.py
new file mode 100644
index 0000000..5af0040
--- /dev/null
+++ b/tests/ImportTimeline.py
@@ -0,0 +1,34 @@
+__all__ = ("log",)
+
+import sys
+from unittest import TestCase
+
+from sideBySideDiff import sideBySideDiff
+
+timeline = []
+
+#from RichConsole import groups
+
+
+def log(msg: str, testInitiated: bool=False):
+ #print((groups.Fore.lightcyanEx if testInitiated else groups.Fore.lightgreenEx)(msg))
+ timeline.append(msg)
+
+
+class ImportTimelineTestCase(TestCase):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.etalon = None
+
+ def log(self, msg):
+ log(msg, True)
+ self.assertTimeline()
+
+ def assertTimeline(self):
+ if timeline != self.etalon[: len(timeline)]:
+ for l in sideBySideDiff(self.etalon[: len(timeline)], timeline, names=("Etalon", "Real")):
+ print(l)
+ self.assertEqual(timeline, self.etalon[: len(timeline)])
+
+ def assertInModulesStatus(self, moduleName):
+ self.log((moduleName, moduleName in sys.modules))
\ No newline at end of file
diff --git a/tests/lazilyTest1/__init__.py b/tests/lazilyTest1/__init__.py
new file mode 100644
index 0000000..98c3aa2
--- /dev/null
+++ b/tests/lazilyTest1/__init__.py
@@ -0,0 +1,18 @@
+from ImportTimeline import log
+
+log("lazilyTest1/__init__.py run")
+import traceback
+
+#traceback.print_stack()
+
+
+def initShit():
+ log("lazilyTest1.__init__.initShit is called")
+
+
+class Abracadabra:
+ __slots__ = ("a",)
+
+ def __init__(self):
+ self.a = 1
+ log(self.__class__.__name__, "constructed")
\ No newline at end of file
diff --git a/tests/lazilyTest1/a.py b/tests/lazilyTest1/a.py
new file mode 100644
index 0000000..cb74f44
--- /dev/null
+++ b/tests/lazilyTest1/a.py
@@ -0,0 +1,15 @@
+from ImportTimeline import log
+
+log("lazilyTest1/a.py run")
+import traceback
+
+#traceback.print_stack()
+
+
+def b():
+ log("lazilyTest1.a.b called")
+
+def getSourceFile():
+ log("lazilyTest1.a.getSourceFile called")
+ from inspect import currentframe, getsourcefile
+ print("lazilyTest1.a.getFrameInfo called: "+str(getsourcefile(currentframe().f_back)))
\ No newline at end of file
diff --git a/tests/lazilyTest1/b.py b/tests/lazilyTest1/b.py
new file mode 100644
index 0000000..65d1f08
--- /dev/null
+++ b/tests/lazilyTest1/b.py
@@ -0,0 +1,8 @@
+from ImportTimeline import log
+
+log("lazilyTest1/b.py run")
+import traceback
+
+#traceback.print_stack()
+
+import lazily.shit.a
\ No newline at end of file
diff --git a/tests/lazilyTest1/submodule/__init__.py b/tests/lazilyTest1/submodule/__init__.py
new file mode 100644
index 0000000..6b01228
--- /dev/null
+++ b/tests/lazilyTest1/submodule/__init__.py
@@ -0,0 +1,8 @@
+from ImportTimeline import log
+
+log("lazilyTest1/submodule/__init__.py run")
+import traceback
+
+#traceback.print_stack()
+def a():
+ log("lazilyTest1.submodule.a is run")
\ No newline at end of file
diff --git a/tests/lazilyTest2/__init__.py b/tests/lazilyTest2/__init__.py
new file mode 100644
index 0000000..1cef50f
--- /dev/null
+++ b/tests/lazilyTest2/__init__.py
@@ -0,0 +1,6 @@
+from ImportTimeline import log
+
+log("lazilyTest2/__init__.py run")
+import traceback
+
+#traceback.print_stack()
\ No newline at end of file
diff --git a/tests/lazilyTest2/a.py b/tests/lazilyTest2/a.py
new file mode 100644
index 0000000..99e0562
--- /dev/null
+++ b/tests/lazilyTest2/a.py
@@ -0,0 +1,6 @@
+from ImportTimeline import log
+
+log("lazilyTest2/a.py run")
+import traceback
+
+#traceback.print_stack()
\ No newline at end of file
diff --git a/tests/lazilyTest2/b.py b/tests/lazilyTest2/b.py
new file mode 100644
index 0000000..a479358
--- /dev/null
+++ b/tests/lazilyTest2/b.py
@@ -0,0 +1,8 @@
+from ImportTimeline import log
+
+log("lazilyTest2/b.py run")
+import traceback
+
+#traceback.print_stack()
+
+import lazily.lazilyTest1.a
\ No newline at end of file
diff --git a/tests/testIdempotency.py b/tests/testIdempotency.py
new file mode 100644
index 0000000..85c8255
--- /dev/null
+++ b/tests/testIdempotency.py
@@ -0,0 +1,40 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testIdempotency(self):
+ count = 2
+ self.etalon = [
+ "import lazily.lazilyTest1.a",
+
+ ("lazilyTest1", False),
+ ("lazilyTest1.a", False),
+ ("lazilyTest1.a.b", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.a.b", False),
+
+ ] * count
+
+ for i in range(count):
+ self.log("import lazily.lazilyTest1.a")
+ import lazily.lazilyTest1.a
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazilyTest1.a.b")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.a.b")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testInterference.py b/tests/testInterference.py
new file mode 100644
index 0000000..f7708d4
--- /dev/null
+++ b/tests/testInterference.py
@@ -0,0 +1,52 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testInterference(self):
+ self.etalon = [
+ "from lazilyTest2 import b",
+ "lazilyTest2/__init__.py run",
+ "lazilyTest2/b.py run",
+ ("lazilyTest1", False),
+ ("lazilyTest1.a", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.b", False),
+
+ "from lazily.lazilyTest1 import a",
+ ("lazilyTest1", False),
+ ("lazilyTest1.a", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.b", False)
+ ]
+
+ self.log("from lazilyTest2 import b")
+ from lazilyTest2 import b
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.b")
+ self.log("from lazily.lazilyTest1 import a")
+
+ from lazily.lazilyTest1 import a
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.b")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testIsInstanceImportFirstInitFirst.py b/tests/testIsInstanceImportFirstInitFirst.py
new file mode 100644
index 0000000..78d34c6
--- /dev/null
+++ b/tests/testIsInstanceImportFirstInitFirst.py
@@ -0,0 +1,42 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testIsInstanceImportFirstInitFirst(self):
+ self.etalon = [
+ "from lazily.lazilyTest1 import Abracadabra",
+ "objectOfLazyClass = Abracadabra()",
+ "lazilyTest1/__init__.py run",
+ "Abracadabra",
+ "from lazilyTest1 import Abracadabra as AbracadabraTrue",
+ "objectOfInitialClass = AbracadabraTrue()",
+ "Abracadabra",
+ ]
+
+
+ self.log("from lazily.lazilyTest1 import Abracadabra")
+ from lazily.lazilyTest1 import Abracadabra
+
+ self.log("objectOfLazyClass = Abracadabra()")
+ objectOfLazyClass = Abracadabra()
+
+ self.log("from lazilyTest1 import Abracadabra as AbracadabraTrue")
+ from lazilyTest1 import Abracadabra as AbracadabraTrue
+
+ self.log("objectOfInitialClass = AbracadabraTrue()")
+ objectOfInitialClass = AbracadabraTrue()
+
+ self.assertIsInstance(objectOfLazyClass, AbracadabraTrue)
+ self.assertIsInstance(objectOfInitialClass, Abracadabra)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testIsInstanceImportFirstInitLast.py b/tests/testIsInstanceImportFirstInitLast.py
new file mode 100644
index 0000000..0495cc5
--- /dev/null
+++ b/tests/testIsInstanceImportFirstInitLast.py
@@ -0,0 +1,42 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testIsInstanceImportFirstInitLast(self):
+ self.etalon = [
+ "from lazily.lazilyTest1 import Abracadabra",
+
+ "from lazilyTest1 import Abracadabra as AbracadabraTrue",
+ "lazilyTest1/__init__.py run",
+ "objectOfInitialClass = AbracadabraTrue()",
+ "Abracadabra",
+ "objectOfLazyClass = Abracadabra()",
+ "Abracadabra",
+ ]
+
+ self.log("from lazily.lazilyTest1 import Abracadabra")
+ from lazily.lazilyTest1 import Abracadabra
+
+ self.log("from lazilyTest1 import Abracadabra as AbracadabraTrue")
+ from lazilyTest1 import Abracadabra as AbracadabraTrue
+
+ self.log("objectOfInitialClass = AbracadabraTrue()")
+ objectOfInitialClass = AbracadabraTrue()
+
+ self.log("objectOfLazyClass = Abracadabra()")
+ objectOfLazyClass = Abracadabra()
+
+ self.assertIsInstance(objectOfLazyClass, AbracadabraTrue)
+ self.assertIsInstance(objectOfInitialClass, Abracadabra)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testIsInstanceImportLastInitLast.py b/tests/testIsInstanceImportLastInitLast.py
new file mode 100644
index 0000000..d48d20e
--- /dev/null
+++ b/tests/testIsInstanceImportLastInitLast.py
@@ -0,0 +1,42 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testIsInstanceImportLastInitLast(self):
+ self.etalon = [
+ "from lazilyTest1 import Abracadabra as AbracadabraTrue",
+ "lazilyTest1/__init__.py run",
+ "objectOfInitialClass = AbracadabraTrue()",
+ "Abracadabra",
+ "from lazily.lazilyTest1 import Abracadabra",
+ "objectOfLazyClass = Abracadabra()",
+ "Abracadabra",
+ ]
+
+
+ self.log("from lazilyTest1 import Abracadabra as AbracadabraTrue")
+ from lazilyTest1 import Abracadabra as AbracadabraTrue
+
+ self.log("objectOfInitialClass = AbracadabraTrue()")
+ objectOfInitialClass = AbracadabraTrue()
+
+ self.log("from lazily.lazilyTest1 import Abracadabra")
+ from lazily.lazilyTest1 import Abracadabra
+
+ self.log("objectOfLazyClass = Abracadabra()")
+ objectOfLazyClass = Abracadabra()
+
+ self.assertIsInstance(objectOfLazyClass, AbracadabraTrue)
+ self.assertIsInstance(objectOfInitialClass, Abracadabra)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testPartialImport.py b/tests/testPartialImport.py
new file mode 100644
index 0000000..9521916
--- /dev/null
+++ b/tests/testPartialImport.py
@@ -0,0 +1,60 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testPartialImport(self):
+ self.etalon = [
+ "from lazily.lazilyTest1.a import b",
+
+ ("lazilyTest1", False),
+ ("lazilyTest1.a", False),
+ ("lazilyTest1.a.b", False), # b is not a module
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.a.b", False), # b is not a module
+
+ "b()",
+ "lazilyTest1/__init__.py run",
+ "lazilyTest1/a.py run",
+ "lazilyTest1.a.b called",
+
+ ("lazilyTest1", True),
+ ("lazilyTest1.a", True),
+ ("lazilyTest1.a.b", False), # b is not a module
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.a.b", False), # b is not a module
+
+ ]
+
+ self.log("from lazily.lazilyTest1.a import b")
+ from lazily.lazilyTest1.a import b
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazilyTest1.a.b")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.a.b")
+
+ self.log("b()")
+ b()
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazilyTest1.a.b")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.a.b")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testSimple.py b/tests/testSimple.py
new file mode 100644
index 0000000..9b1a980
--- /dev/null
+++ b/tests/testSimple.py
@@ -0,0 +1,62 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testSimple(self):
+ self.etalon = [
+
+ "import lazily.lazilyTest1.a",
+
+ ("lazilyTest1", False),
+ ("lazilyTest1.a", False),
+ ("lazilyTest1.a.b", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.a.b", False),
+
+ "lazily.lazilyTest1.a.b()",
+
+ "lazilyTest1/__init__.py run",
+ "lazilyTest1/a.py run",
+ "lazilyTest1.a.b called",
+
+ ("lazilyTest1", True),
+ ("lazilyTest1.a", True),
+ ("lazilyTest1.a.b", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.a", True),
+ ("lazily.lazilyTest1.a.b", False), # it is not a module and is not imported
+ ]
+
+
+ self.log("import lazily.lazilyTest1.a")
+ import lazily.lazilyTest1.a
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazilyTest1.a.b")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.a.b")
+
+ self.log("lazily.lazilyTest1.a.b()")
+ lazily.lazilyTest1.a.b()
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.a")
+ self.assertInModulesStatus("lazilyTest1.a.b")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.a")
+ self.assertInModulesStatus("lazily.lazilyTest1.a.b")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testSubmoduleInterference.py b/tests/testSubmoduleInterference.py
new file mode 100644
index 0000000..d99ce86
--- /dev/null
+++ b/tests/testSubmoduleInterference.py
@@ -0,0 +1,76 @@
+import sys
+from pathlib import Path
+import unittest
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+from ImportTimeline import ImportTimelineTestCase
+
+
+class Tests(ImportTimelineTestCase):
+ def testSimple(self):
+ self.etalon = [
+ "import lazily.lazilyTest1",
+
+ ("lazilyTest1", False),
+ ("lazilyTest1.submodule", False),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.submodule", False),
+
+ "lazily.lazilyTest1.initShit()", # causes initialization of lazily.lazilyTest1 with lazily
+ "lazilyTest1/__init__.py run",
+ "lazilyTest1.__init__.initShit is called",
+ "from lazilyTest1.submodule import a",
+ "lazilyTest1/submodule/__init__.py run",
+
+ "a()",
+ "lazilyTest1.submodule.a is run",
+
+ ("lazilyTest1", True),
+ ("lazilyTest1.submodule", True),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.submodule", False),
+
+ "from lazily.lazilyTest1.submodule import a",
+ ("lazilyTest1", True),
+ ("lazilyTest1.submodule", True),
+ ("lazily.lazilyTest1", True),
+ ("lazily.lazilyTest1.submodule", True),
+ ]
+
+
+ self.log("import lazily.lazilyTest1")
+ import lazily.lazilyTest1
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.submodule")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.submodule")
+
+ self.log("lazily.lazilyTest1.initShit()")
+ lazily.lazilyTest1.initShit()
+
+ self.log("from lazilyTest1.submodule import a")
+ from lazilyTest1.submodule import a
+
+ self.log("a()")
+ a()
+
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.submodule")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.submodule")
+
+ from lazily.lazilyTest1.submodule import a
+
+ self.log("from lazily.lazilyTest1.submodule import a")
+ self.assertInModulesStatus("lazilyTest1")
+ self.assertInModulesStatus("lazilyTest1.submodule")
+ self.assertInModulesStatus("lazily.lazilyTest1")
+ self.assertInModulesStatus("lazily.lazilyTest1.submodule")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/testThirdPartInterference.py b/tests/testThirdPartInterference.py
new file mode 100644
index 0000000..27503eb
--- /dev/null
+++ b/tests/testThirdPartInterference.py
@@ -0,0 +1,21 @@
+import sys
+from pathlib import Path
+import unittest
+import os
+
+thisDir = Path(__file__).parent.absolute()
+sys.path.insert(0, str(thisDir.parent))
+sys.path.insert(0, str(thisDir))
+
+class Tests(unittest.TestCase):
+ def testThirdPartyInterference(self):
+ self.etalon = [
+ ]
+
+ from lazily.functools import partial
+ import csv
+ os.stat(csv.__file__)
+
+
+if __name__ == "__main__":
+ unittest.main()