Skip to content

Commit

Permalink
🎨 format code using pre-commit tooling
Browse files Browse the repository at this point in the history
  • Loading branch information
GLEF1X committed Jul 20, 2022
1 parent 5c198ab commit dfdacc1
Show file tree
Hide file tree
Showing 26 changed files with 267 additions and 210 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ jobs:
with:
file: coverage.xml
flags: unittests
name: py-${{ matrix.python-version }}-${{ matrix.os }}
name: py-${{ matrix.python-version }}-${{ matrix.os }}
2 changes: 1 addition & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ jobs:
uses: pypa/gh-action-pypi-publish@master
with:
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
password: ${{ secrets.PYPI_TOKEN }}
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,4 @@ dmypy.json
.env

docker_test/*
docker_test
docker_test
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ repos:
- id: check-yaml
- id: debug-statements
- id: double-quote-string-fixer
- id: requirements-txt-fixer
- id: requirements-txt-fixer
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,3 @@ if __name__ == '__main__':
main()

```

11 changes: 8 additions & 3 deletions apscheduler_di/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from ._binding import UnableToResolveDependencyError
from .decorator import ContextSchedulerDecorator

__maintainer__ = "GLEF1X"
__maintainer__ = 'GLEF1X'

__version__ = "0.0.4"
__version__ = '0.0.4'

__all__ = ('ContextSchedulerDecorator', "__maintainer__", "__version__", "UnableToResolveDependencyError")
__all__ = (
'ContextSchedulerDecorator',
'__maintainer__',
'__version__',
'UnableToResolveDependencyError',
)
35 changes: 20 additions & 15 deletions apscheduler_di/_binding.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import functools
import inspect
from inspect import Signature, _ParameterKind
from typing import TypeVar, Callable, Any, Dict, get_type_hints, List
from typing import Any, Callable, Dict, List, TypeVar, get_type_hints

from rodi import Services, CannotResolveTypeException, GetServiceContext
from rodi import CannotResolveTypeException, GetServiceContext, Services

T = TypeVar("T", bound=Callable[..., Any])
T = TypeVar('T', bound=Callable[..., Any])


class NormalizationError(Exception):
...


class ParamSpec:
__slots__ = ("name", "annotation", "kind", "default", "_str")
__slots__ = ('name', 'annotation', 'kind', 'default', '_str')

def __init__(self, name, annotation, kind, default, str_repr):
self.name = name
Expand All @@ -29,20 +29,23 @@ def __str__(self) -> str:
class UnsupportedSignatureError(NormalizationError):
def __init__(self, method: Callable[..., Any]):
super().__init__(
f"Cannot normalize method `{method.__qualname__}` because its "
f"signature contains *args, or *kwargs, or keyword only parameters. "
f"If you use a decorator, please use `functools.@wraps` "
f"with your wrapper, to fix this error."
f'Cannot normalize method `{method.__qualname__}` because its '
f'signature contains *args, or *kwargs, or keyword only parameters. '
f'If you use a decorator, please use `functools.@wraps` '
f'with your wrapper, to fix this error.'
)


class UnableToResolveDependencyError(Exception):
def __init__(self, message: str, third_party_di_lib_exception: Exception):
super().__init__(f"Unable to resolve the dependency: {message}")
super().__init__(f'Unable to resolve the dependency: {message}')
self.third_party_di_lib_exception = third_party_di_lib_exception


def normalize_job_executable(func: Callable[..., Any], services: Services, ) -> Callable[..., Any]:
def normalize_job_executable(
func: Callable[..., Any],
services: Services,
) -> Callable[..., Any]:
check_if_signature_is_supported(func)

if inspect.iscoroutinefunction(func) or inspect.iscoroutine(func):
Expand All @@ -57,8 +60,8 @@ def check_if_signature_is_supported(func: Callable[..., Any]) -> None:
params = get_func_param_specs(func)

if any(
str(param).startswith("*") or param.kind.value == _ParameterKind.KEYWORD_ONLY
for param in params.values()
str(param).startswith('*') or param.kind.value == _ParameterKind.KEYWORD_ONLY
for param in params.values()
):
raise UnsupportedSignatureError(func)

Expand All @@ -80,8 +83,8 @@ def get_func_param_specs(method: Callable[..., Any]) -> Dict[str, ParamSpec]:


def _get_method_annotations_or_throw(method: Callable[..., Any]) -> Dict[str, Any]:
method_locals = getattr(method, "_locals", None)
method_globals = getattr(method, "_globals", None)
method_locals = getattr(method, '_locals', None)
method_globals = getattr(method, '_globals', None)
return get_type_hints(method, globalns=method_globals, localns=method_locals)


Expand All @@ -101,7 +104,9 @@ async def wrapper(*args, **kwargs):
return wrapper


def resolve_dependencies(services: Services, func: Callable[..., Any], **kwargs: Any) -> List[Any]:
def resolve_dependencies(
services: Services, func: Callable[..., Any], **kwargs: Any
) -> List[Any]:
dependencies = []
for param_spec in get_func_param_specs(func).values():
with GetServiceContext() as context:
Expand Down
10 changes: 3 additions & 7 deletions apscheduler_di/_events.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import functools
from typing import (
Any,
Callable,
)
from typing import Any, Callable

from apscheduler.schedulers.base import BaseScheduler
from rodi import Container
Expand All @@ -14,15 +11,14 @@ def __init__(self, scheduler: BaseScheduler, ctx: Container, on_event: int) -> N
self._on_event = on_event
self._ctx = ctx

def __iadd__(self, handler: Callable[..., Any]) -> "ApschedulerEvent":
def __iadd__(self, handler: Callable[..., Any]) -> 'ApschedulerEvent':
with_context = functools.partial(handler, ctx=self._ctx)
self._scheduler.add_listener(callback=with_context, mask=self._on_event)
return self

def __isub__(self, handler: Callable[..., Any]) -> "ApschedulerEvent":
def __isub__(self, handler: Callable[..., Any]) -> 'ApschedulerEvent':
self._scheduler.remove_listener(callback=handler)
return self

def __len__(self) -> int:
return len(self._scheduler._listeners) # noqa

7 changes: 4 additions & 3 deletions apscheduler_di/_helper.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from typing import Tuple, Any, Dict, Callable
from typing import Any, Callable, Dict, Tuple

from apscheduler_di._binding import get_func_param_specs


def get_missing_arguments(func: Callable[..., Any], args: Tuple[Any, ...],
kwargs: Dict[Any, Any]) -> Dict[str, None]:
def get_missing_arguments(
func: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[Any, Any]
) -> Dict[str, None]:
"""
Get arguments to skip ValueError with traceback "The following arguments have not been supplied"
It raises, because we injecting our dependencies using functools.wraps and do not change
Expand Down
17 changes: 11 additions & 6 deletions apscheduler_di/_inject.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,20 @@
def inject_dependencies_to_scheduler(scheduler: BaseScheduler, ctx: Container):
prepared_context = ctx.build_provider()
for job_store in scheduler._jobstores.values(): # type: BaseJobStore # noqa

def func_get_due_jobs_with_context(c: BaseJobStore, now: datetime):
jobs: List[Job] = type(job_store).get_due_jobs(c, now)
return _convert_raw_to_easy_maintainable_jobs(scheduler, jobs, prepared_context)
return _convert_raw_to_easy_maintainable_jobs(
scheduler, jobs, prepared_context
)

job_store.get_due_jobs = types.MethodType(func_get_due_jobs_with_context, job_store)
job_store.get_due_jobs = types.MethodType(
func_get_due_jobs_with_context, job_store
)


def _convert_raw_to_easy_maintainable_jobs(
scheduler: BaseScheduler,
jobs: List[Job],
ctx: Services
scheduler: BaseScheduler, jobs: List[Job], ctx: Services
) -> List[Job]:
unsafe_pickling = False
if isinstance(scheduler, BlockingScheduler):
Expand All @@ -39,7 +42,9 @@ def _convert_raw_to_easy_maintainable_jobs(
return jobs


def _make_jobs_shared(jobs: List[Job], scheduler: BaseScheduler, ctx: Services) -> List[SharedJob]:
def _make_jobs_shared(
jobs: List[Job], scheduler: BaseScheduler, ctx: Services
) -> List[SharedJob]:
shared_jobs: List[SharedJob] = []
for job in jobs:
if isinstance(job, SharedJob):
Expand Down
21 changes: 10 additions & 11 deletions apscheduler_di/_serialization.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pickle
from typing import Callable, Any
from typing import Any, Callable

from apscheduler.job import Job
from apscheduler.schedulers.base import BaseScheduler
Expand All @@ -16,17 +16,16 @@ def _load_func_from_ref(func_ref: str, ctx: Services) -> Callable[..., Any]:


class SharedJob(Job):

def __init__(self, scheduler: BaseScheduler, ctx: Services, **kwargs):
fn_args = kwargs.get("args", ())
fn_kwargs = kwargs.get("kwargs", {})
fn = kwargs["func"]
fn_args = kwargs.get('args', ())
fn_kwargs = kwargs.get('kwargs', {})
fn = kwargs['func']
if not callable(fn):
fn = ref_to_obj(fn)
kwargs["kwargs"].update(get_missing_arguments(fn, fn_args, fn_kwargs))
kwargs['kwargs'].update(get_missing_arguments(fn, fn_args, fn_kwargs))

if kwargs.get("version") is not None:
kwargs.pop("version") # pragma: no cover
if kwargs.get('version') is not None:
kwargs.pop('version') # pragma: no cover
super().__init__(scheduler, **kwargs)
self.kwargs = {}
self._ctx = ctx
Expand All @@ -39,10 +38,10 @@ def __getstate__(self):
def __setstate__(self, state):
if state.get('version', 1) > 1:
raise ValueError( # pragma: no cover
'Job has version %s, but only version 1 can be handled' %
state['version']
'Job has version %s, but only version 1 can be handled'
% state['version']
)
self._ctx = pickle.loads(state["ctx"])
self._ctx = pickle.loads(state['ctx'])
self.id = state['id']
self.func_ref = state['func']
self.args = state['args']
Expand Down
Loading

0 comments on commit dfdacc1

Please sign in to comment.