Skip to content
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
19 changes: 19 additions & 0 deletions jsonrpcserver/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,26 @@ def add(self, *args: Any, **kwargs: Any) -> Optional[Callable]:
@methods.add
def subtract(minuend, subtrahend):
return minuend - subtrahend

@methods.add(name='divide')
def division(dividend, divisor):
return dividend / divisor
"""
if "name" in kwargs and isinstance(kwargs["name"], str):
return self._parameterized_add(*args, **kwargs)
else:
return self._batch_add(*args, **kwargs)

def _parameterized_add(self, name: str) -> Callable:
def decorator(method):
assert callable(method)
self.items[name] = method

return method

return decorator

def _batch_add(self, *args: Any, **kwargs: Any) -> Optional[Callable]:
# Multiple loops here, but due to changes in dictionary comprehension evaluation
# order in Python 3.8 (PEP 572), we need to validate separately from the
# dictionary comprehension. Otherwise different exceptions will be raised in 3.8
Expand Down
10 changes: 10 additions & 0 deletions tests/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,16 @@ def foo():
assert methods.items["foo"] is foo


def test_add_function_custom_name_via_decorator():
methods = Methods()

@methods.add(name='bar')
def foo():
pass

assert methods.items["bar"] is foo


def test_add_static_method_via_decorator():
methods = Methods()

Expand Down