A decorator for debugging purposes. Shows the call arguments, result
    and instructions as they are runned.
486101
def debug(trace=True, backtrace=1, other=None, output=sys.stderr):
    """"""
    from pprint import pprint
    import traceback
    def debugdeco(func):
        def tracer(frame, event, arg):
            print>>output, '--- Tracer: %s, %r' % (event, arg)
            traceback.print_stack(frame, 1, output)
            return tracer
        def wrapped(*a, **k):
            print>>output
            print>>output, '--- Calling %s.%s with:' % (
                getattr(func, '__module__', ''),
                func.__name__
            )
            for i in enumerate(a):
                print>>output, '    | %s: %s' % i
            print>>output, '    | ',
            pprint(k, output)
            print>>output, '    From:'
            for i in traceback.format_stack(sys._getframe(1), backtrace):
                print>>output, i,
            if other:
                print>>output, '---      [ %r ]' % (other(func,a,k))
            if trace: sys.settrace(tracer)
            ret = func(*a, **k)
            if trace: sys.settrace(None)
            #~ a = list(a)
            print>>output, '--- %s.%s returned: %r' % (
                getattr(func, '__module__', ''),
                func.__name__,
                #~ ret not in a and ret or "ARG%s"%a.index(ret)
                ret
            )
            return ret
        return wrapped
    return debugdeco
907312
def parse_decorators(self):
        
        name = []
        arguments = []
        at_arguments = False

        while self.current is not None:
            self.log.debug("parsing decorators, current token is %r (%s)",
                           self.current.kind, self.current.value)
            if (self.current.kind == tk.NAME and
                    self.current.value in ['def', 'class']):
                # Done with decorators - found function or class proper
                break
            elif self.current.kind == tk.OP and self.current.value == '@':
                # New decorator found. Store the decorator accumulated so far:
                self._accumulated_decorators.append(
                    Decorator(''.join(name), ''.join(arguments)))
                # Now reset to begin accumulating the new decorator:
                name = []
                arguments = []
                at_arguments = False
            elif self.current.kind == tk.OP and self.current.value == '(':
                at_arguments = True
            elif self.current.kind == tk.OP and self.current.value == ')':
                # Ignore close parenthesis
                pass
            elif self.current.kind == tk.NEWLINE or self.current.kind == tk.NL:
                # Ignore newlines
                pass
            else:
                # Keep accumulating current decorator's name or argument.
                if not at_arguments:
                    name.append(self.current.value)
                else:
                    arguments.append(self.current.value)
            self.stream.move()

        # Add decorator accumulated so far
        self._accumulated_decorators.append(
            Decorator(''.join(name), ''.join(arguments)))
72058
def _log (fun, msg, args, **kwargs):
    
    fun(msg, *args)
    if kwargs.get("traceback"):
        # note: get rid of last parts of the stack
        fun(_stack_format(inspect.stack()[2:]))
    if kwargs.get("exception"):
        fun(traceback.format_exc())
939951
def deprecated(instructions):
    
    def decorator(func):
        """This is a decorator which can be used to mark functions as deprecated.

        It will result in a warning being emitted when the function is used.
        """
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            message = 'Call to deprecated function {}. {}'.format(func.__name__,
                                                                  instructions)
            frame = inspect.currentframe().f_back
            warnings.warn_explicit(message,
                                   category=DeprecatedWarning,
                                   filename=inspect.getfile(frame.f_code),
                                   lineno=frame.f_lineno)
            return func(*args, **kwargs)
        return wrapper
    return decorator
1015459
def debug(message, *args, **kwargs):
    
    if 'end' in kwargs:
        end = kwargs['end']
    else:
        end = '\n'

    if DEBUG: 
        if len(args) == 0:
            sys.stderr.write(message)
        else:
            sys.stderr.write(message % args)

        sys.stderr.write(end)
        sys.stderr.flush()
414979
def trace(fn): # pragma: no cover
    
    def wrapped(*args, **kwargs):
        msg = []
        msg.append('Enter {}('.format(fn.__name__))

        if args:
            msg.append(', '.join([str(x) for x in args]))

        if kwargs:
            kwargs_str = ', '.join(['{}={}'.format(k, v) for k, v in list(kwargs.items())])
            if args:
                msg.append(', ')
            msg.append(kwargs_str)
        msg.append(')')
        print(''.join(msg))
        ret = fn(*args, **kwargs)
        print('Return {}'.format(ret))
        return ret
    return wrapped
756998
def show(cls, result):
        
        if result.ok:
            if result.stdout:
                out = '\n'.join(result.stdout)
                if result.value and result.value != '()':
                    return '\n'.join([out, result.value])
                return out
            if result.value and not cls._is_function_value(result.value):
                return result.value
            return cls.show_type(result)
        return result.value
1004567
def trace(f):
    
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        print 'Calling ' + f.func_name + ' in ' + str(args[0])
        return f(*args, **kwargs)
    return decorator
601723
def map_arg(**maps):
    
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if six.PY2:
                argmap = inspect.getcallargs(func, *args, **kwargs)
            else:
                # getcallargs was deprecated since 3.5
                sig = inspect.signature(func)
                argmap = sig.bind_partial(*args, **kwargs).arguments
            for k, map_func in six.iteritems(maps):
                if k in argmap:
                    argmap[k] = map_func(argmap[k])
            return func(**argmap)
        return wrapper
    return deco
5678
def make_wrapper(self, callable_):
        """"""
        assert callable(callable_)
        def wrapper(*args, **kw):
            return self.call_and_report_errors(callable_, *args, **kw)
        return wrapper
124082
def autobuild_decorate(func, caller):
    
    evaldict = dict(_call_=caller, _func_=func)
    fun = AutobuildFunctionMaker.create(
        func, "return _call_(_func_, %(shortsignature)s)",
        evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun
824790
def subtask(*args, **kwargs):
    '''
    '''
    depth = kwargs.get('depth', 2)
    prefix = kwargs.get('prefix', '\n' + '#' * depth + ' ')
    tail = kwargs.get('tail', '\n')
    doc1 = kwargs.get('doc1', False)
    color = kwargs.get('color', cyan)

    def real_decorator(func):
        if doc1:
            return print_full_name(color=color, prefix=prefix,
                                   tail=tail)(print_doc1(func))
        return print_full_name(color=color, prefix=prefix, tail=tail)(func)

    invoked = bool(not args or kwargs)
    if not invoked:
        # invoke decorator function which returns the wrapper function
        return real_decorator(func=args[0])
    return real_decorator
991434
def with_formatter(formatter):
    
    def _decorator_after_args(unwrapped):
        def _wrapped(self, *args, **kwargs):
            logging.debug('unwrapped: %s', unwrapped)
            logging.debug('self: %s', self)
            logging.debug('args: %s', args)
            logging.debug('kwargs: %s', kwargs)
            return_value = unwrapped(self, *args, **kwargs)
            if 'raw' in kwargs and kwargs['raw']:
                return return_value
            else:
                return formatter(return_value)
        return _wrapped
    return _decorator_after_args
1025374
def _make_decorator(measuring_func):
    """"""
    def _decorator(name = None, metric = call_default):
        def wrapper(func):

            name_ = name if name is not None else func.__module__ + '.' +func.__name__
            class instrument_decorator(object): # must be a class for descriptor magic to work
                @wraps(func)
                def __call__(self, *args, **kwargs):
                    return measuring_func(func(*args, **kwargs), name_, metric)

                def __get__(self, instance, class_):
                    name_ = name if name is not None else\
                        ".".join((class_.__module__, class_.__name__, func.__name__))
                    @wraps(func)
                    def wrapped_method(*args, **kwargs):
                        return measuring_func(func(instance, *args, **kwargs), name_, metric)
                    return wrapped_method
            return instrument_decorator()

        return wrapper
    return _decorator
1228701
def debug_callback(event, *args, **kwds):
    '''
    '''
    l = ['event %s' % (event.type,)]
    if args:
        l.extend(map(str, args))
    if kwds:
        l.extend(sorted('%s=%s' % t for t in kwds.items()))
    print('Debug callback (%s)' % ', '.join(l))
1141324
def trace_emit(self):
        
        def decorator(f):
            self.tracer.emitter = f
            return f
        return decorator
689780
def describe_arguments(func):
    

    argspec = inspect.getargspec(func)
    # we should probably raise an exception somewhere if func includes **kwargs
    if argspec.defaults:
        positional_args = argspec.args[:-len(argspec.defaults)]
        keyword_names = argspec.args[-len(argspec.defaults):]
        for arg, default in zip(keyword_names, argspec.defaults):
            yield ('--{}'.format(arg),), {'default': default}
    else:
        positional_args = argspec.args

    for arg in positional_args:
        yield (arg,), {}
    if argspec.varargs:
        yield (argspec.varargs,), {'nargs': '*'}