Skip to content

Commit

Permalink
Merge pull request #22 from madnesspie/sync-context-manager-improvements
Browse files Browse the repository at this point in the history
Sync context manager improvements
  • Loading branch information
madnesspie committed Jun 8, 2020
2 parents b3c3206 + 0dfab5e commit 322636b
Show file tree
Hide file tree
Showing 7 changed files with 35 additions and 22 deletions.
2 changes: 2 additions & 0 deletions .isort.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[settings]
force_single_line = true
2 changes: 1 addition & 1 deletion obm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = "0.0.20"
__version__ = "0.0.21"
14 changes: 12 additions & 2 deletions obm/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from decimal import Decimal
from typing import List, Union
from typing import List
from typing import Union

from obm import connectors
from obm import utils


class ConnectorMixin:
class SyncContextManagerMixin:
def __enter__(self):
return utils.sync_run(self.__aenter__())

def __exit__(self, exc_type, exc, tb):
return utils.sync_run(self.__aexit__(exc_type, exc, tb))


class NodeMixin(SyncContextManagerMixin):

__connector = None

Expand Down
2 changes: 1 addition & 1 deletion obm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def create_for(cls, connector_name: str):
return cls(name=connectors.MAPPING[connector_name].currency)


class Node(mixins.ConnectorMixin):
class Node(mixins.NodeMixin):
def __init__(
self,
name: str,
Expand Down
25 changes: 8 additions & 17 deletions obm/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
methods they way they should be ran, but it's incredibly useful for quick
scripts and the runtime overhead is relatively low.
"""
import asyncio
import functools
import inspect

from obm import mixins, models
from obm import mixins
from obm import models
from obm import utils

__all__ = ["models", "mixins"]

Expand All @@ -33,35 +34,25 @@ def _syncify_wrap(_type, method_name):
@functools.wraps(method)
def syncified(*args, **kwargs):
coro = method(*args, **kwargs)
loop = asyncio.get_event_loop()
if loop.is_running():
return coro
return loop.run_until_complete(coro)

def optional_rename(name):
return (
name.replace("a", "")
if name in ["__aenter__", "__aexit__"]
else name
)
return utils.sync_run(coro)

# Save an accessible reference to the original method
syncified.asynchronous = method
setattr(_type, optional_rename(method_name), syncified)
setattr(_type, method_name, syncified)


def syncify(*types):
"""Converts all async methods in given types into synchronous.
Converted methods return either the coroutine or the result
Converted methods return eith er the coroutine or the result
based on whether asyncio's event loop is running.
"""
for _type in types:
for name in dir(_type):
if not name.startswith("_") or name in ["__aexit__", "__aenter__"]:
if not name.startswith("_"):
# TODO: Move to __slots__
if inspect.iscoroutinefunction(getattr(_type, name)):
_syncify_wrap(_type, name)


syncify(mixins.ConnectorMixin, mixins.TransactionMixin)
syncify(mixins.NodeMixin, mixins.TransactionMixin)
10 changes: 10 additions & 0 deletions obm/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import asyncio
import inspect


def sync_run(coro, loop=None):
assert inspect.iscoroutine(coro)
loop = loop or asyncio.get_event_loop()
if loop.is_running():
return coro
return loop.run_until_complete(coro)
2 changes: 1 addition & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ expected-line-ending-format=
bad-functions=map,filter,input

# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,f,e,_,tx,pk,pytestmark,pytest_plugins
good-names=i,j,k,f,e,_,tx,pk,tb,pytestmark,pytest_plugins

# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
Expand Down

0 comments on commit 322636b

Please sign in to comment.