Skip to content
Snippets Groups Projects
Commit 7e6a7495 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

refactor

parent f87fbb9f
No related branches found
No related tags found
No related merge requests found
......@@ -4,15 +4,13 @@ Just useful objects to make your coding nicer every day
"""
from __future__ import print_function, absolute_import, division
from .concurrent import Monitor, RMonitor, CallableGroup
from .algos import merge_dicts
from .monitor import Monitor, RMonitor
from .structures import TimeBasedHeap, CallableGroup, Heap
from .recast_exceptions import rethrow_as, silence_excs
from .typecheck import typed, List, Tuple, Dict, NewType, Callable, Sequence, \
TypeVar, Generic, Mapping, Iterable, Union, Any, Optional, CallSignature, \
Number, coerce
from .recast_exceptions import rethrow_as, silence_excs
from .typednamedtuple import typednamedtuple
from .structures import TimeBasedHeap, Heap, typednamedtuple
__all__ = [
'typednamedtuple',
......
# coding=UTF-8
from __future__ import absolute_import
from .monitor import *
from .callablegroup import *
# coding=UTF-8
from __future__ import print_function, absolute_import, division
import six
import logging
from ..typecheck import typed
logger = logging.getLogger(__name__)
__all__ = [
'CallableGroup',
]
class CallableGroup(object):
"""
This behaves like a function, but allows to add other functions to call
when invoked, eg.
c1 = Callable()
c1.add(foo)
c1.add(bar)
c1(2, 3)
Now both foo and bar will be called with arguments (2, 3). Their exceptions
will be propagated.
"""
# todo not threadsafe with oneshots
def __init__(self, gather=False, swallow_exceptions=False):
"""
:param gather: if True, results from all callables will be gathered
into a list and returned from __call__
:param swallow_exceptions: if True, exceptions from callables will be
silently ignored. If gather is set,
result will be the exception instance
"""
self.callables = [] # tuple of (callable, oneshot)
self.gather = gather
self.swallow_exceptions = swallow_exceptions
@typed(None, Callable, bool)
def add(self, callable, oneshot=False):
"""
:param oneshot: if True, callable will be unregistered after single call
"""
self.callables.append((callable, oneshot))
def __call__(self, *args, **kwargs):
"""
Run the callable. All registered callables will be called with
passed arguments, so they should have the same arity.
If callables raise, it will be passed through.
:return: list of results if gather was set, else None
"""
clbl = self.callables # for moar thread safety
self.callables = []
if self.gather:
results = []
for callable, oneshot in clbl:
try:
q = callable(*args, **kwargs)
except Exception as e:
if not self.swallow_exceptions:
raise # re-raise
q = e
if self.gather:
results.append(q)
if not oneshot:
self.callables.append((callable, oneshot))
if self.gather:
return results
import functools
import threading
__all__ = [
'Monitor', 'RMonitor'
]
class Monitor(object):
"""
......
# coding=UTF-8
from __future__ import print_function, absolute_import, division
import six
import logging
from .structures import *
from .typednamedtuple import *
......@@ -8,7 +8,7 @@ import logging
import six
from .typecheck import typed, Callable, Iterable
from satella.coding.typecheck import typed, Callable, Iterable
logger = logging.getLogger(__name__)
......@@ -22,76 +22,6 @@ returns_bool = typed(returns=bool)
returns_iterable = typed(returns=Iterable)
class CallableGroup(object):
"""
This behaves like a function, but allows to add other functions to call
when invoked, eg.
c1 = Callable()
c1.add(foo)
c1.add(bar)
c1(2, 3)
Now both foo and bar will be called with arguments (2, 3). Their exceptions
will be propagated.
"""
# todo not threadsafe with oneshots
def __init__(self, gather=False, swallow_exceptions=False):
"""
:param gather: if True, results from all callables will be gathered
into a list and returned from __call__
:param swallow_exceptions: if True, exceptions from callables will be
silently ignored. If gather is set,
result will be the exception instance
"""
self.callables = [] # tuple of (callable, oneshot)
self.gather = gather
self.swallow_exceptions = swallow_exceptions
@typed(None, Callable, bool)
def add(self, callable, oneshot=False):
"""
:param oneshot: if True, callable will be unregistered after single call
"""
self.callables.append((callable, oneshot))
def __call__(self, *args, **kwargs):
"""
Run the callable. All registered callables will be called with
passed arguments, so they should have the same arity.
If callables raise, it will be passed through.
:return: list of results if gather was set, else None
"""
clbl = self.callables # for moar thread safety
self.callables = []
if self.gather:
results = []
for callable, oneshot in clbl:
try:
q = callable(*args, **kwargs)
except Exception as e:
if not self.swallow_exceptions:
raise # re-raise
q = e
if self.gather:
results.append(q)
if not oneshot:
self.callables.append((callable, oneshot))
if self.gather:
return results
def _extras_to_one(fun):
@functools.wraps(fun)
......
# coding=UTF-8
from __future__ import print_function, absolute_import, division
import six
import functools
import itertools
import logging
from collections import namedtuple
from .typecheck import typed, coerce, CallSignature
logger = logging.getLogger(__name__)
__all__ = [
'typednamedtuple',
]
def _nth(it, n):
return [x[n] for x in it]
def _adjust(q):
var, type_ = q
if type_ in (None, 'self') or isinstance(var, type_):
......@@ -28,11 +26,25 @@ def typednamedtuple(cls_name, *arg_name_type):
Fields will be coerced to type passed in the pair.
Parameters are tuples of (field name, class/constructor as callable/1)
For example:
tnt = typednamedtuple('tnt', ('x', float), ('y', float))
a = tnt('5.0', y=2)
a.x is float, a.y is float too
"""
fieldnames = _nth(arg_name_type, 0)
typeops = _nth(arg_name_type, 1)
fieldnames = []
typeops = []
mapping = {}
for name, type_ in arg_name_type:
fieldnames.append(name)
typeops.append(type_)
mapping[name] = type_
MyCls = namedtuple(cls_name, fieldnames)
mapping = dict(arg_name_type)
class Wrapper(MyCls):
__doc__ = MyCls.__doc__
......@@ -45,13 +57,12 @@ def typednamedtuple(cls_name, *arg_name_type):
try:
nargs.append(_adjust((kwargs.pop(next_field_name), mapping[next_field_name])))
except KeyError:
raise ValueError('Field %s not given', next_field_name)
raise TypeError('Field %s not given', next_field_name)
if len(kwargs) > 0:
raise ValueError('Too many parameters')
raise TypeError('Too many parameters')
return MyCls.__new__(MyCls, *nargs)
return Wrapper
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment