Drill through layers of decorators attempting to locate the actual argspec
    for a method.
167301
def getargspec(method):
    

    argspec = _getargspec(method)
    args = argspec[0]
    if args and args[0] == 'self':
        return argspec
    if hasattr(method, '__func__'):
        method = method.__func__

    func_closure = six.get_function_closure(method)

    # NOTE(sileht): if the closure is None we cannot look deeper,
    # so return actual argspec, this occurs when the method
    # is static for example.
    if not func_closure:
        return argspec

    closure = None
    # In the case of deeply nested decorators (with arguments), it's possible
    # that there are several callables in scope;  Take a best guess and go
    # with the one that looks most like a pecan controller function
    # (has a __code__ object, and 'self' is the first argument)
    func_closure = filter(
        lambda c: (
            six.callable(c.cell_contents) and
            hasattr(c.cell_contents, '__code__')
        ),
        func_closure
    )
    func_closure = sorted(
        func_closure,
        key=lambda c: 'self' in c.cell_contents.__code__.co_varnames,
        reverse=True
    )

    closure = func_closure[0]

    method = closure.cell_contents
    return getargspec(method)
1265718
def _TypecheckDecorator(subject=None, **kwargs):
  
  if subject is None:
    return _TypecheckDecoratorFactory(kwargs)
  elif inspect.isfunction(subject) or inspect.ismethod(subject):
    return _TypecheckFunction(subject, {}, 2, None)
  else:
    raise TypeError()
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
40991
def check_all_params_are_keyword(method):
    

    args, varargs, keywords, defaults = inspect.getargspec(method)

    # Always have self, thus the -1
    if len(args or []) - 1 != len(defaults or []):
        raise CooperativeError, "Init has positional parameters " + \
              str(args[1:])
    if varargs:
        raise CooperativeError, "Init has variadic positional parameters"
    if keywords:
        raise CooperativeError, "Init has variadic keyword parameters"
604434
def decorate_method(cls, func):
        
        func_args = [arg for arg in function_arguments(func) if arg != 'self']
        method_return_types = \
            Endpoint._parse_function_return_types_from_doc(func.__doc__)
        name = '%s.%s' % (cls.path, func.__name__)

        @wraps(func)
        def method_decorator(self, *args, **kwargs):
            for i in range(len(args)):
                kwargs[func_args[i]] = args[i]

            api_call = self.connection._pre_process_call(
                name, endpoint_params=kwargs)
            try:
                data = func(**kwargs)
            except RestException as e:
                api_call.error = e
                raise e

            except Exception as e:
                call_queue = self.connection._call_queue.get(
                    self.connection._get_thread_id(), [])
                if api_call in call_queue:
                    call_queue.remove(api_call)
                e = RestException(original_error=e,
                                  stack=traceback.format_exc())
                log.error('ApiCall Exception: %s' % e, exc_info=True)
                raise e
            return self.connection._post_process_call(
                api_call, data, method_return_types)

        method_decorator.rest_method = True
        return method_decorator
463945
def get_args(method_or_func):
    """"""
    try:
        # Python 3.0+
        args = list(inspect.signature(method_or_func).parameters.keys())
    except AttributeError:
        # Python 2.7
        args = inspect.getargspec(method_or_func).args
    return args
106777
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
              'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call_=caller, _decorate_=decorate)
    return FunctionMaker.create(
        '%s(func)' % name, 'return _decorate_(func, _call_)',
        evaldict, doc=doc, module=caller.__module__,
        __wrapped__=caller)
288233
def parametrized_class(decorator):
    ''''''

    def decorator_builder(*args, **kwargs):

        def meta_decorator(cls):
            return decorator(cls, *args, **kwargs)

        return meta_decorator

    return decorator_builder
965710
def default_should_trace_hook(frame, filename):
    '''
    
    '''
    # First, check whether this code object has a cached value
    ignored_lines = _filename_to_ignored_lines.get(filename)
    if ignored_lines is None:
        # Now, look up that line of code and check for a @DontTrace
        # preceding or on the same line as the method.
        # E.g.:
        # #@DontTrace
        # def test():
        #     pass
        #  ... or ...
        # def test(): #@DontTrace
        #     pass
        ignored_lines = {}
        lines = linecache.getlines(filename)
        for i_line, line in enumerate(lines):
            j = line.find('#')
            if j >= 0:
                comment = line[j:]
                if DONT_TRACE_TAG in comment:
                    ignored_lines[i_line] = 1
                    
                    #Note: when it's found in the comment, mark it up and down for the decorator lines found.
                    k = i_line - 1
                    while k >= 0:
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k -= 1
                        else:
                            break
                        
                    k = i_line + 1
                    while k <= len(lines):
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k += 1
                        else:
                            break
                        

        _filename_to_ignored_lines[filename] = ignored_lines

    func_line = frame.f_code.co_firstlineno - 1 # co_firstlineno is 1-based, so -1 is needed
    return not (
        func_line - 1 in ignored_lines or #-1 to get line before method 
        func_line in ignored_lines)
324075
def decorator_of_context_manager(ctxt):
    

    def decorator_fn(*outer_args, **outer_kwargs):
        def decorator(fn):
            @functools.wraps(fn)
            def wrapper(*args, **kwargs):
                with ctxt(*outer_args, **outer_kwargs):
                    return fn(*args, **kwargs)

            return wrapper

        return decorator

    if getattr(ctxt, "__doc__", None) is None:
        msg = "Decorator that runs the inner function in the context of %s"
        decorator_fn.__doc__ = msg % ctxt
    else:
        decorator_fn.__doc__ = ctxt.__doc__
    return decorator_fn
1328160
def get_kwargs_defaults(argspec):
    """"""
    arg_names = tuple(argspec.args)
    defaults = argspec.defaults or ()
    num_args = len(argspec.args) - len(defaults)
    kwargs_defaults = {}
    for i, default_value in enumerate(defaults):
        kwargs_defaults[arg_names[num_args + i]] = default_value
    if getattr(argspec, "kwonlydefaults", None):
        kwargs_defaults.update(argspec.kwonlydefaults)
    return kwargs_defaults
70438
def getargspecs(func):
    
    if func is None:
        raise TypeError('None is not a Python function')
    if hasattr(func, 'ch_func'):
        return getargspecs(func.ch_func)
    elif hasattr(func, 'ov_func'):
        return getargspecs(func.ov_func)
    if hasattr(inspect, 'getfullargspec'):
        return inspect.getfullargspec(func) # Python 3
    else:
        return inspect.getargspec(func)
1320659
def decorator(target):
    """"""

    def decorate(fn):
        spec = inspect.getargspec(fn)
        names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
        targ_name, fn_name = unique_symbols(names, 'target', 'fn')

        metadata = dict(target=targ_name, fn=fn_name)
        metadata.update(format_argspec_plus(spec, grouped=False))

        code = 'lambda %(args)s: %(target)s(%(fn)s, %(apply_kw)s)' % (
                metadata)
        decorated = eval(code, {targ_name: target, fn_name: fn})
        decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
        return update_wrapper(decorated, fn)
    return update_wrapper(decorate, target)
682650
def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']:
    
    while hasattr(func, "__wrapped__"):
        yield func

        func = getattr(func, "__wrapped__")

    yield func
410927
def noargs(self):
        ""
        noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
        return self.argspec == noargs
1353593
def _get_argspec(f):
    
    if sys.version_info[0] < 3:
        argspec = inspect.getargspec(f)
    else:
        # `getargspec` is deprecated since python3.0 (incompatible with function annotations).
        # See SPARK-23569.
        argspec = inspect.getfullargspec(f)
    return argspec
615977
def _infer_decorator_callchain(node):
    
    if not isinstance(node, FunctionDef):
        return None
    if not node.parent:
        return None
    try:
        result = next(node.infer_call_result(node.parent))
    except exceptions.InferenceError:
        return None
    if isinstance(result, bases.Instance):
        result = result._proxied
    if isinstance(result, ClassDef):
        if result.is_subtype_of("%s.classmethod" % BUILTINS):
            return "classmethod"
        if result.is_subtype_of("%s.staticmethod" % BUILTINS):
            return "staticmethod"
    return None