Ejemplo n.º 1
0
 def __init__(self, bindings=[], context=None):
     self.bindings = []
     if context is None:
         context = _get_caller_globals()
     self.parser = Parser(context)
     for pattern, handler in bindings:
         self.register(pattern, handler)
Ejemplo n.º 2
0
def match_args(pattern, context=None):
    """
    Decorator for matching a function's arglist.

    :param pattern: Pattern or str -- the pattern
    :param context: dict -- an optional context for the pattern parser. If
        absent, it defaults to the caller's `globals()`.

    Usage:

        >>> @match_args('head::tail')
        ... def do_something(head, tail):
        ...     return (head, tail)
        >>> do_something(1, 2, 3, 4)
        (1, (2, 3, 4))

    """
    if isinstance(pattern, _basestring):
        if context is None:
            context = _get_caller_globals()
        pattern = Parser(context)(pattern)
    def wrapper(function):
        @wraps(function)
        def f(*args):
            match = pattern.match(args)
            if not match:
                raise NoMatch("%s doesn't match %s" % (pattern, args))
            return function(**match.ctx)
        return f
    return wrapper
Ejemplo n.º 3
0
 def __init__(self, bindings=[], context=None):
     self.bindings = []
     if context is None:
         context = _get_caller_globals()
     self.parser = Parser(context)
     for pattern, handler in bindings:
         self.register(pattern, handler)
Ejemplo n.º 4
0
def match_args(pattern, context=None):
    """
    Decorator for matching a function's arglist.

    :param pattern: Pattern or str -- the pattern
    :param context: dict -- an optional context for the pattern parser. If
        absent, it defaults to the caller's `globals()`.

    Usage:

        >>> @match_args('head::tail')
        ... def do_something(head, tail):
        ...     return (head, tail)
        >>> do_something(1, 2, 3, 4)
        (1, (2, 3, 4))

    """
    if isinstance(pattern, _basestring):
        if context is None:
            context = _get_caller_globals()
        pattern = Parser(context)(pattern)

    def wrapper(function):
        @wraps(function)
        def f(*args):
            match = pattern.match(args)
            if not match:
                raise NoMatch("%s doesn't match %s" % (pattern, args))
            return function(**match.ctx)

        return f

    return wrapper
Ejemplo n.º 5
0
 def __call__(self, pattern, context=None):
     if isinstance(pattern, _basestring):
         if context is None:
             context = _get_caller_globals()
         pattern = Parser(context)(pattern)
     return _UnpackerHelper(self.__dict__, pattern)
Ejemplo n.º 6
0
 def __call__(self, pattern, context=None):
     if isinstance(pattern, _basestring):
         if context is None:
             context = _get_caller_globals()
         pattern = Parser(context)(pattern)
     return _UnpackerHelper(self.__dict__, pattern)