Return valid kwargs to function func
439338
def get_valid_kwargs(func, potential_kwargs):
    
    kwargs = {}
    for name in get_kwarg_names(func):
        with suppress(KeyError):
            kwargs[name] = potential_kwargs[name]
    return kwargs
1147866
def get_func_result_cachekey(func_, args_=tuple(), kwargs_={}):
    
    import utool as ut
    # Rectify partials and whatnot
    true_args = args_
    true_kwargs = kwargs_
    true_func = func_
    if isinstance(func_, partial):
        true_func = func_.func
        if func_.args is not None:
            true_args = tuple(list(func_.args) + list(args_))
        if func_.keywords is not None:
            true_kwargs.update(func_.keywords)

    if ut.is_method(true_func):
        method = true_func
        true_func = method.im_func
        self = method.im_self
        true_args = tuple([self] + list(true_args))

    # Build up cachekey
    funcname = ut.get_funcname(true_func)
    kwdefaults = ut.get_kwdefaults(true_func, parse_source=False)
    #kwdefaults = ut.get_kwdefaults(true_func, parse_source=True)
    argnames   = ut.get_argnames(true_func)
    key_argx = None
    key_kwds = None
    func = true_func  # NOQA
    args = true_args  # NOQA
    kwargs = true_kwargs  # NOQA
    args_key = ut.get_cfgstr_from_args(true_func, true_args, true_kwargs,
                                       key_argx, key_kwds, kwdefaults,
                                       argnames)
    cachekey = funcname + '(' + args_key + ')'
    return cachekey
182471
def get_functarguments(func):
    
    argspec = inspect.getargspec(func)
    if argspec.defaults is not None:
        args = argspec.args[:-len(argspec.defaults)]
        kwargs = dict(
            zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
    else:
        args = argspec.args
        kwargs = {}
    if args and args[0] == 'self':
        args.pop(0)
    func.__named__ = []
    arguments = []
    shared = get_shared(func)
    for arg in args:
        if has_shared(arg, shared) is not False:
            continue
        if has_argument(arg, func.__cls__) is not False:
            continue
        arguments.append(([arg], {}, ))
        func.__named__.append(arg)
    for key, val in kwargs.items():
        if has_shared(key, shared) is not False:
            continue
        if has_argument(key, func.__cls__) is not False:
            continue
        if isinstance(val, dict):
            flags = [val.pop('lflag', '--%s' % key)]
            short = val.pop('flag', None)
            dest = val.get('dest', key).replace('-', '_')
            if short:
                flags.insert(0, short)
        else:
            flags = ['--%s' % key]
            val = dict(default=val)
            dest = key.replace('-', '_')
        func.__named__.append(dest)
        arguments.append((flags, val, ))
    return arguments
1153125
def func_old_kwargs(a, b=None, **kwargs):  # pylint: disable=invalid-name
    """"""

    # We extract a specific optional parameter from **kwargs
    try:
        c = kwargs['c']
    except KeyError:
        c = None

    return a, b, c
202950
def self_if_parameters(func):
    
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if args or kwargs:
            return self
        else:
            return result
    return wrapper
1029855
def get_function_call_str(fn, args, kwargs):
    """"""

    def str_converter(v):
        try:
            return str(v)
        except Exception:
            try:
                return repr(v)
            except Exception:
                return "<n/a str raised>"

    result = get_full_name(fn) + "("
    first = True
    for v in args:
        if first:
            first = False
        else:
            result += ","
        result += str_converter(v)
    for k, v in kwargs.items():
        if first:
            first = False
        else:
            result += ","
        result += str(k) + "=" + str_converter(v)
    result += ")"
    return result
1298685
def get_func_kwargs(func, recursive=True):
    
    import utool as ut
    argspec = ut.get_func_argspec(func)
    if argspec.defaults is None:
        header_kw = {}
    else:
        header_kw = dict(zip(argspec.args[::-1], argspec.defaults[::-1]))
    if argspec.keywords is not None:
        header_kw.update(dict(ut.recursive_parse_kwargs(func)))
    return header_kw
934485
def check_types(func):
    
    call = PythonCall(func)

    @wraps(func)
    def decorator(*args, **kwargs):
        parameters = call.bind(args, kwargs)
        for arg_name, expected_type in func.__annotations__.items():
            if not isinstance(parameters[arg_name], expected_type):
                raise TypeError("{} must be a {}".format(
                    arg_name, expected_type))
        return call.apply(args, kwargs)
    return decorator
1094903
def arg_lookup(fun, aspec=None):
    '''
    
    '''
    ret = {'kwargs': {}}
    if aspec is None:
        aspec = get_function_argspec(fun)
    if aspec.defaults:
        ret['kwargs'] = dict(zip(aspec.args[::-1], aspec.defaults[::-1]))
    ret['args'] = [arg for arg in aspec.args if arg not in ret['kwargs']]
    return ret
475645
def get_default_args(func):
    
    args, varargs, keywords, defaults = getargspec_no_self(func)
    return dict(zip(args[-len(defaults):], defaults))
503472
def get_kwarg_names(func):
    
    sig = inspect.signature(func)
    kwonlyargs = [p.name for p in sig.parameters.values()
                  if p.default is not p.empty]
    return kwonlyargs
577000
def get_func_args(func):
    
    if isinstance(func, functools.partial):
        return _signature(func.func)
    if inspect.isfunction(func) or inspect.ismethod(func):
        return _signature(func)
    # Callable class
    return _signature(func.__call__)
217492
def decorator(func):
  
  """
  def wrapper(__decorated__=None, *Args, **KwArgs):
    if __decorated__ is None: # the decorator has some optional arguments.
      return lambda _func: func(_func, *Args, **KwArgs)

    else:
      return func(__decorated__, *Args, **KwArgs)

  return wrap(wrapper, func)
605625
def mk_kwargs(cls, kwargs):
        
        ret = {}
        kws = ['row_factory', 'body', 'parent']
        for k in kws:
            if k in kwargs:
                ret[k] = kwargs.pop(k)

        return ret
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
1335947
def debug(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("{} args: {} kwargs: {}".format(func.__name__, args, kwargs))
        return func(*args, **kwargs)

    return wrapper
1128164
def get_kwargs(self):
        """"""
        return {k: v for k, v in vars(self).items() if k not in self._ignored}