Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding python<=3.9 support #52

Merged
merged 9 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,38 +34,38 @@
autoclass_content = "both"

sys.setrecursionlimit(500)
project = 'pyoload'
copyright = '2024, ken-morel'
author = 'ken-morel'
project = "pyoload"
copyright = "2024, ken-morel"
author = "ken-morel"

release = '2.0.0'
version = '2.0.0'
release = "2.0.0"
version = "2.0.0"

# -- General configuration

extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
"sphinx.ext.duration",
"sphinx.ext.doctest",
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
]

intersphinx_mapping = {
'python': ('https://docs.python.org/3/', None),
'sphinx': ('https://www.sphinx-doc.org/en/master/', None),
'github': ('https://github.com/', None),
"python": ("https://docs.python.org/3/", None),
"sphinx": ("https://www.sphinx-doc.org/en/master/", None),
"github": ("https://github.com/", None),
}
intersphinx_disabled_domains = ['std']
intersphinx_disabled_domains = ["std"]

templates_path = ['_templates']
templates_path = ["_templates"]

# -- Options for HTML output

html_theme = "sphinxawesome_theme"

# -- Options for EPUB output
epub_show_urls = 'footnote'
epub_show_urls = "footnote"

rst_prolog = """\
.. role:: python(code)
Expand Down
69 changes: 37 additions & 32 deletions src/pyoload/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,18 @@
from inspect import getmodule
from inspect import isclass
from inspect import signature
from types import UnionType
from typing import get_origin
from typing import get_args
from typing import Any
from typing import Callable
from typing import GenericAlias
from typing import Type
from typing import Union

try:
from typing import NoneType
from types import NoneType
except ImportError:
NoneType = None
NoneType = type(None)


class AnnotationError(ValueError):
Expand Down Expand Up @@ -343,20 +346,19 @@ def cast(val: Any, totype: Any) -> Any:
:returns: An instance of the casting type
"""
if isinstance(totype, GenericAlias):
if totype.__origin__ == dict:
if len(totype.__args__) == 2:
kt, vt = totype.__args__
elif len(totype.__args__) == 1:
kt, vt = Any, totype.__args__[1]
return {
Cast.cast(k, kt): Cast.cast(v, vt) for k, v in val.items()
}
args = get_args(totype)
if get_origin(totype) == dict:
if len(args) == 2:
kt, vt = args
elif len(args) == 1:
kt, vt = args[0], Any
return {Cast.cast(k, kt): Cast.cast(v, vt) for k, v in val.items()}
else:
sub = totype.__args__[0]
return totype.__origin__([Cast.cast(v, sub) for v in val])
if isinstance(totype, UnionType):
sub = args[0]
return get_origin(totype)([Cast.cast(v, sub) for v in val])
if get_origin(totype) is Union:
errors = []
for subtype in totype.__args__:
for subtype in get_args(totype):
try:
return Cast.cast(val, subtype)
except Exception as e:
Expand Down Expand Up @@ -485,14 +487,16 @@ def typeMatch(val: Any, spec: Any) -> bool:
else:
return True
elif isinstance(spec, GenericAlias):
if not isinstance(val, spec.__origin__):
orig = get_origin(spec)
if not isinstance(val, orig):
return False

if spec.__origin__ == dict:
if len(spec.__args__) == 2:
kt, vt = spec.__args__
elif len(spec.__args__) == 1:
kt, vt = Any, spec.__args__[1]
if orig == dict:
args = get_args(spec)
if len(args) == 2:
kt, vt = args
elif len(args) == 1:
kt, vt = Any, args[1]
else:
return True

Expand All @@ -502,15 +506,15 @@ def typeMatch(val: Any, spec: Any) -> bool:
else:
return True
else:
sub = spec.__args__[0]
sub = get_args(spec)[0]
for val in val:
if not typeMatch(val, sub):
return False
else:
return True


def resolveAnnotations(obj: Type | Callable) -> None:
def resolveAnnotations(obj: Callable) -> None:
"""
Evaluates all the stringized annotations of the argument

Expand Down Expand Up @@ -628,7 +632,7 @@ def wrapper(*pargs, **kw):


def unannotate(func: Callable) -> Callable:
if hasattr(func, '__pyod_annotate__'):
if hasattr(func, "__pyod_annotate__"):
return func.__pyod_annotate__
else:
return func
Expand All @@ -644,17 +648,17 @@ def annotable(func: Callable) -> Callable:


def is_annotable(func):
return not hasattr(func, '__pyod_annotable__') or func.__pyod_annotable__
return not hasattr(func, "__pyod_annotable__") or func.__pyod_annotable__


def is_annoted(func):
return hasattr(func, '__pyod_annotate__')
return hasattr(func, "__pyod_annotate__")


__overloads__: dict[str, list[Callable]] = {}


def overload(func: Callable, name: str | None = None) -> Callable:
def overload(func: Callable, name: str = None) -> Callable:
"""
returns a wrapper over the passed function
which typechecks arguments on each call
Expand Down Expand Up @@ -705,7 +709,7 @@ def wrapper(*args, **kw):
return wrapper


def annotateClass(cls: Any):
def annotateClass(cls: Any, recur: bool = True):
"""
Annotates a class object, wrapping and replacing over it's __setattr__
and typechecking over each attribute assignment.
Expand All @@ -714,11 +718,12 @@ def annotateClass(cls: Any):
it recursively annotates the classes methods except `__pyod_norecur__`
attribute is defines
"""

if isinstance(cls, bool):
return partial(annotateClass, recur=cls)
if not hasattr(cls, "__annotations__"):
cls.__annotations__ = {}
if isinstance(cls, bool):
return partial(annotate, recur=cls)
recur = not hasattr(cls, "__pyod_norecur__")
recur = not hasattr(cls, "__pyod_norecur__") and recur
setter = cls.__setattr__
if recur:
for x in dir(cls):
Expand All @@ -736,7 +741,7 @@ def annotateClass(cls: Any):

@wraps(cls.__setattr__)
def new_setter(self: Any, name: str, value: Any) -> Any:
if any(isinstance(x, str) for x in self.__annotations__.values()):
if str in map(type, self.__annotations__.values()):
resolveAnnotations(self)

if name not in self.__annotations__:
Expand Down
90 changes: 40 additions & 50 deletions src/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,95 +7,85 @@
project_dir = Path(__file__).parent

try:
long_description = (project_dir / 'README.md').read_text()
long_description = (project_dir / "README.md").read_text()
except FileNotFoundError:
try:
long_description = Path('README.md').read_text()
long_description = Path("README.md").read_text()
except FileNotFoundError:
try:
long_description = Path('/src/README.md').read_text()
long_description = Path("/src/README.md").read_text()
except FileNotFoundError:
long_description = (project_dir.parent / 'README.md').read_text()
long_description = (project_dir.parent / "README.md").read_text()

deps = ()

extra_flake8 = (
'flake8',
'flake8-commas',
'flake8-quotes',
'flake8-multiline-containers',
"flake8",
"flake8-commas",
"flake8-quotes",
"flake8-multiline-containers",
)

extra_test = (
'pytest',
'pytest-cov',
"pytest",
"pytest-cov",
)

extra_dev = (
*extra_flake8,
# *extra_flake8,
*extra_test,
)

extra_ci = (
*extra_flake8,
# *extra_flake8,
*extra_test,
'coveralls',
"coveralls",
)

setup(
name='pyoload',
name="pyoload",
version=__version__,
packages=find_packages(exclude=['tests', 'tests.*']),
packages=find_packages(exclude=["tests", "tests.*"]),
project_urls={
'Documentation': 'https://pyoload.readthedocs.io/',
'Funding': 'https://ko-fi.com/kenmorel',
'Source': 'https://github.com/ken-morel/pyoload/',
'Tracker': 'https://github.com/ken-morel/pyoload/issues',
"Documentation": "https://pyoload.readthedocs.io/",
"Funding": "https://ko-fi.com/kenmorel",
"Source": "https://github.com/ken-morel/pyoload/",
"Tracker": "https://github.com/ken-morel/pyoload/issues",
},
url='https://github.com/ken-morel/pyoload',
license='MIT',
author='ken-morel',
author_email='engonken8@gmail.com',
maintainer='ken-morel',
maintainer_email='engonken8@gmail.com',
url="https://github.com/ken-morel/pyoload",
license="MIT",
author="ken-morel",
author_email="engonken8@gmail.com",
maintainer="ken-morel",
maintainer_email="engonken8@gmail.com",
description=(
'Python package for function argument overload,'
' typechecking and casting'
"Python package for function argument overload," " typechecking and casting"
),
long_description=long_description,
long_description_content_type='text/markdown',

long_description_content_type="text/markdown",
install_requires=deps,
extras_require={
'dev': extra_dev,
'ci': extra_ci,
"dev": extra_dev,
"ci": extra_ci,
},

classifiers=[
# See https://pypi.org/classifiers/

'Intended Audience :: Developers',

"Intended Audience :: Developers",
# 'Development Status :: 1 - Planning',
# 'Development Status :: 2 - Pre-Alpha',
'Development Status :: 3 - Alpha',
"Development Status :: 3 - Alpha",
# 'Development Status :: 4 - Beta',
# 'Development Status :: 5 - Production/Stable',
# 'Development Status :: 6 - Mature',
# 'Development Status :: 7 - Inactive',

'License :: OSI Approved :: MIT License',

'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',

'Natural Language :: English',

'Topic :: Software Development :: Libraries :: Python Modules',
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Natural Language :: English",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
7 changes: 7 additions & 0 deletions src/tests/logs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
typeMatch vs isinstance on int:True 0.26837916ms
typeMatch vs isinstance on int:False 0.24146669ms
typeMatch on dict[str, int]*50:True 29.45430688ms
typeMatch on dict[str, int]*50:False 5.970363880000001ms
Cast str->int: 2.92456138ms
Cast complex->int | str: 0.12061774399999999ms
Cast dict[int,list[str]*10]*10->dict[str,tuple[float]]: 2.7908898460000002ms
7 changes: 4 additions & 3 deletions src/tests/test_annotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

from pyoload import annotate

assert pyoload.__version__ == '2.0.0'
assert pyoload.__version__ == "2.0.0"


@annotate
def foo(a, b=3, c: str = 'R') -> int:
def foo(a, b=3, c: str = "R") -> int:
assert b == 3
assert isinstance(c, str)
return 3
Expand All @@ -15,5 +15,6 @@ def foo(a, b=3, c: str = 'R') -> int:
def test_annotate():
foo(2)

if __name__ == '__main__':

if __name__ == "__main__":
test_annotate()
Loading
Loading