Python inspect 模块,_empty() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用inspect._empty()

项目:pytc-gui    作者:harmslab    | 项目源码 | 文件源码
def get_connector_param(self,avail_name):
        """
        Look up parameters for a initializing a connector.
        """

        try:
            c = self._avail_connectors[avail_name]
        except KeyError:
            err = "connector {} not found\n".format(avail_name)
            raise ValueError(err)

        meta = {}
        parameters = inspect.signature(c).parameters
        for k in parameters:
            meta[k] = parameters.default
            if meta[k] == inspect._empty:
                meta[k] = None

        return meta
项目:territoriali-backend    作者:algorithm-ninja    | 项目源码 | 文件源码
def get_handler_params(handle):
        if hasattr(handle, HandlerParams.HANDLER_PARAMS_ATTR):
            return getattr(handle, HandlerParams.HANDLER_PARAMS_ATTR)
        params = {}
        sign = inspect.signature(handle).parameters

        for name in sign:
            if name == "self": continue
            type = sign[name].annotation if sign[name].annotation is not inspect._empty else None
            req = sign[name].default == inspect._empty

            params[name] = {
                "type": type,
                "required": req
            }
        return params
项目:speccer    作者:bensimner    | 项目源码 | 文件源码
def return_annotation(self):
        r = self.signature.return_annotation
        if r is not inspect._empty:
            return r
        return None
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def get_signature(func):
            sig = inspect.signature(func)
            pk = inspect._ParameterKind
            has_var_args = any(p.kind == pk.VAR_POSITIONAL for p in sig.parameters.values())
            has_var_kwds = any(p.kind == pk.VAR_KEYWORD for p in sig.parameters.values())
            all_keyword_params = [param_name for param_name, param in sig.parameters.items()
                                  if param.kind in (pk.POSITIONAL_OR_KEYWORD, pk.KEYWORD_ONLY)]
            default_params = [param_name for param_name, param in sig.parameters.items()
                                  if param.kind in (pk.POSITIONAL_OR_KEYWORD, pk.KEYWORD_ONLY) and param.default != inspect._empty]
            return _Signature(all_keyword_params, default_params, has_var_args, has_var_kwds)
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def get_signature(func):
            sig = inspect.signature(func)
            has_var_args = any(p.kind == inspect._VAR_POSITIONAL for p in sig.parameters.values())
            has_var_kwds = any(p.kind == inspect._VAR_KEYWORD for p in sig.parameters.values())
            all_keyword_params = [param_name for param_name, param in sig.parameters.items()
                                  if param.kind in (inspect._POSITIONAL_OR_KEYWORD, inspect._KEYWORD_ONLY)]
            default_params = [param_name for param_name, param in sig.parameters.items()
                                  if param.kind in (inspect._POSITIONAL_OR_KEYWORD, inspect._KEYWORD_ONLY) and param.default != inspect._empty]
            return _Signature(all_keyword_params, default_params, has_var_args, has_var_kwds)
项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
def __init__(self):
        self.signal = None
        self.indices = None
        self.methods = METHODS
        self.method_names = [method.__name__ for method in METHODS]
        self.params = {method.__name__: OrderedDict(
            [(p.name, p.default) for p in
             inspect.signature(method).parameters.values() if
             p.default is not inspect._empty]) for method in METHODS}
        self._method = self.method_names[0]
项目:decorated_options    作者:musically-ut    | 项目源码 | 文件源码
def optioned(option_arg='_opts'):
    """Returns a decorator which can 'fill-in' the arguments to function 'f' using the
    option passed in with the name given by `option_arg` parameter.

    :param: option_arg: The name of the argument which will contain the Options object.
    """
    def _decorator(f):
        sig = inspect.signature(f)
        params = sig.parameters
        f_args = params.keys()

        @wraps(f)
        def wrapped_f(*args, **kwargs):
            if option_arg not in kwargs:
                return f(*args, **kwargs)
            else:
                opts = kwargs[option_arg]
                all_args_dict = opts._get_dict()
                all_args_dict.update(kwargs)

                new_arg_dict = {}
                for idx, arg in enumerate(f_args):
                    if idx < len(args):
                        # This argument was passed positionally, ignore
                        pass
                    else:
                        if arg in all_args_dict:
                            new_arg_dict[arg] = all_args_dict[arg]
                        elif params[arg].default is not inspect._empty:
                            new_arg_dict[arg] = params[arg].default

                return f(*args, **new_arg_dict)

        return wrapped_f

    return _decorator
项目:firefly    作者:rorodata    | 项目源码 | 文件源码
def generate_signature(self, f):
        func_sig = signature(f)
        params = []

        for param_name, param_obj in func_sig.parameters.items():
            param = {
                "name": param_name,
                "kind": str(param_obj.kind)
            }
            if param_obj.default is not _empty:
                param["default"] = param_obj.default
            params += [param]

        return params
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def sign_nargs(fun):
        return sum([y.default is inspect._empty for x,y in inspect.signature(fun).parameters.items() if x != 'self'])
项目:aiocache    作者:argaen    | 项目源码 | 文件源码
def _get_args_dict(func, args, kwargs):
    defaults = {
        arg_name: arg.default for arg_name, arg in inspect.signature(func).parameters.items()
        if arg.default is not inspect._empty   # TODO: bug prone..
    }
    args_names = func.__code__.co_varnames[:func.__code__.co_argcount]
    return {**defaults, **dict(zip(args_names, args)), **kwargs}
项目:crowddynamics    作者:jaantollander    | 项目源码 | 文件源码
def empty_to_none(value):
    """Convert parameter.empty to none"""
    return None if value is inspect._empty else value
项目:wrf-python    作者:NCAR    | 项目源码 | 文件源码
def _apply_defaults(bound):
    """Set default values for missing arguments.

    For variable-positional arguments (*args) the default is an
    empty tuple.

    For variable-keyword arguments (**kwargs) the default is an
    empty dict.

    Args:

        bound (:class:`inspect.BoundArguments`): A BoundArguments object.

    Returns:

        None

    """
    arguments = bound.arguments

    new_arguments = []
    for name, param in bound._signature.parameters.items():
        try:
            new_arguments.append((name, arguments[name]))
        except KeyError:
            if param.default is not _empty:
                val = param.default
            elif param.kind is _VAR_POSITIONAL:
                val = ()
            elif param.kind is _VAR_KEYWORD:
                val = {}
            else:
                # This BoundArguments was likely produced by
                # Signature.bind_partial().
                continue
            new_arguments.append((name, val))

    bound.arguments = OrderedDict(new_arguments)
项目:server    作者:happypandax    | 项目源码 | 文件源码
def _add_capture_handler(self, handler, node=None):
        assert callable(handler)
        assert node is None or isinstance(PluginNode)

        capture_dict = self._capture_handlers
        if not node:
            capture_dict = self.default_capture_handlers

        sig = inspect.signature(handler)

        if 'capture' in sig.parameters:
            cap = sig.parameters['capture'].default

            if not cap == inspect._empty:

                if not isinstance(cap, (list, tuple)):
                    cap = (cap,)

                for c in cap:
                    if c not in capture_dict:
                        capture_dict[c] = []

                    if node:
                        capture_dict[c].append((node, handler))
                    else:
                        capture_dict[c].append(handler)
项目:PyAcid    作者:Acid-ZdS    | 项目源码 | 文件源码
def _get_command_desc(name):
    try:
        fn = REPL.get_command(name)
    except KeyError:
        print('Error: command {!r} is not defined.'.format(name))

    if fn.__doc__ is not None:
        doc = fn.__doc__.strip()
    else:
        doc = 'No documentation available for this command'

    arg_desc = ''
    sig = inspect.signature(fn)

    # ignore the self parameter
    for pname, param in list(sig.parameters.items())[1:]:
        if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
            if param.default == inspect._empty:
                arg_desc += '<{}> '.format(pname)
            elif param.default is None:
                arg_desc += '[{}] '.format(pname)
            else:
                arg_desc += '[{}={!r}] '.format(pname, param.default)
        elif param.kind == inspect.Parameter.POSITIONAL_ONLY:
            arg_desc += '[{} ...] '.format(pname)
        else:
            # dirty :(
            pass

    desc = ':{name} {args}'.format(
        name=name,
        args=arg_desc
    )
    return '{desc:<30}\t\t{doc}'.format(
        desc=desc,
        doc=doc
    )
项目:function-pattern-matching    作者:rasguanabana    | 项目源码 | 文件源码
def _getfullargspec_p(func):
    """Gets uniform full arguments specification of func, portably."""

    try:
        sig = inspect.signature(func)
        sig_params = sig.parameters
    except AttributeError: # signature method not available
        # try getfullargspec is present (pre 3.3)
        try:
            arg_spec = inspect.getfullargspec(func)
        except AttributeError: # getfullargspec method not available
            arg_spec = inspect.getargspec(func) # py2, trying annotations will fail.

    else: # continue conversion for py >=3.3
        arg_spec = SimpleNamespace() # available since 3.3, just like signature, so it's ok to use it here.

        def _arg_spec_helper(kinds=(), defaults=False, kwonlydefaults=False, annotations=False):
            for arg_name, param in sig_params.items():
                if not defaults and not kwonlydefaults and not annotations and param.kind in kinds:
                    yield arg_name
                elif sum((defaults, kwonlydefaults, annotations)) > 1:
                    raise ValueError("Only one of 'defaults', 'kwonlydefaults' or 'annotations' can be True simultaneously")
                elif annotations and param.annotation is not inspect._empty:
                    yield (arg_name, param.annotation)
                elif param.default is not inspect._empty:
                    if defaults and param.kind in (p_kind.POSITIONAL_OR_KEYWORD, p_kind.POSITIONAL_ONLY):
                        yield param.default
                    elif kwonlydefaults and param.kind is p_kind.KEYWORD_ONLY:
                        yield (arg_name, param.default)

        arg_spec.args = tuple(_arg_spec_helper((p_kind.POSITIONAL_OR_KEYWORD, p_kind.POSITIONAL_ONLY)))
        arg_spec.varargs = six.next(_arg_spec_helper((p_kind.VAR_POSITIONAL,)), None)
        arg_spec.kwonlyargs = tuple(_arg_spec_helper((p_kind.KEYWORD_ONLY,)))
        arg_spec.varkw = six.next(_arg_spec_helper((p_kind.VAR_KEYWORD,)), None)
        arg_spec.keywords = arg_spec.varkw # getargspec compat
        arg_spec.defaults = tuple(_arg_spec_helper(defaults=True)) or None
        arg_spec.kwonlydefaults = dict(_arg_spec_helper(kwonlydefaults=True))
        arg_spec.annotations = dict(_arg_spec_helper(annotations=True))
        if sig.return_annotation is not inspect._empty:
            arg_spec.annotations['return'] = sig.return_annotation

    return arg_spec
项目:xarray_filters    作者:ContinuumIO    | 项目源码 | 文件源码
def get_args_kwargs_defaults(func):
    '''Get the required args, defaults, and var keywords of func

    Parameters
    ----------

    func: callable

    Returns
    -------

    tuple of 3 elements:
        args: Positional argument names
        kwargs: Keyword arguments and their defaults
        takes_var_keywords: True if func takes variable keywords

    Examples
    --------

    TODO
    '''
    if hasattr(inspect, 'signature'):
        sig = inspect.signature(func) # Python 3
        empty = inspect._empty
    else:
        import funcsigs
        sig = funcsigs.signature(func) # Python 2
        empty = funcsigs._empty
    params = sig.parameters
    kwargs = {}
    args = []
    takes_variable_keywords = None
    for k, v in params.items():
        if v.default != empty:
            kwargs[k] = v.default
        else:
            args.append(k)
        if v.kind == 4:
            #<_ParameterKind.VAR_KEYWORD: 4>
            takes_variable_keywords = k

        '''sig = inspect.getargpsec(func) # Python 2
        args = sig.args
        kwargs = sig.keywords
        called = None
        for x in range(100):
            test_args = (func,) + tuple(range(x))
            try:
                called = inspect.getcallargs(*test_args)
                break
            except:
                pass
        if called is None:
            raise
        '''
    return args, kwargs, takes_variable_keywords
项目:knack    作者:Microsoft    | 项目源码 | 文件源码
def extract_args_from_signature(operation, excluded_params=None):
    """ Extracts basic argument data from an operation's signature and docstring
        excluded_params: List of params to ignore and not extract. By default we ignore ['self', 'kwargs'].
    """
    args = []
    try:
        # only supported in python3 - falling back to argspec if not available
        sig = inspect.signature(operation)
        args = sig.parameters
    except AttributeError:
        sig = inspect.getargspec(operation)  # pylint: disable=deprecated-method
        args = sig.args

    arg_docstring_help = option_descriptions(operation)
    excluded_params = excluded_params or ['self', 'kwargs']

    for arg_name in [a for a in args if a not in excluded_params]:
        try:
            # this works in python3
            default = args[arg_name].default
            required = default == inspect.Parameter.empty  # pylint: disable=no-member
        except TypeError:
            arg_defaults = (dict(zip(sig.args[-len(sig.defaults):], sig.defaults))
                            if sig.defaults
                            else {})
            default = arg_defaults.get(arg_name)
            required = arg_name not in arg_defaults

        action = 'store_' + str(not default).lower() if isinstance(default, bool) else None

        try:
            default = (default
                       if default != inspect._empty  # pylint: disable=protected-access, no-member
                       else None)
        except AttributeError:
            pass

        options_list = ['--' + arg_name.replace('_', '-')]
        help_str = arg_docstring_help.get(arg_name)

        yield (arg_name, CLICommandArgument(arg_name,
                                            options_list=options_list,
                                            required=required,
                                            default=default,
                                            help=help_str,
                                            action=action))
项目:slack-today-i-did    作者:eeue56    | 项目源码 | 文件源码
def test_save_and_load_known_user_func_history(mocker, bot, message_context):
    dangerous_commands = ('reload', 'reload-funcs')
    default_args = ('channel',)
    sample_args = {
        int: 'NUM 1',
        str: 'orange',
        datetime.datetime: 'NOW',
        typing.List[str]: 'FOR blurb,blabi',
        inspect._empty: 'help', # guessing it's help's `args` param
    }

    expected_func_names = []

    for command, func in bot.known_user_functions().items():
        if command in dangerous_commands:
            continue

        signature = inspect.signature(func)
        args = (sample_args[param.annotation]
                for (name, param) in signature.parameters.items()
                if name not in default_args)
        message_text = f'{command} {" ".join(args)}'.strip()

        with message_context(bot, sender=MOCK_PERSON):
            spy = mocker.spy(bot, func.__name__)
            mocker.patch.object(bot.rollbar, 'get_item_by_counter', return_value={})
            mocker.patch.object(bot, 'repo')

            # preserve important attributes on the spy
            functools.update_wrapper(spy, func)
            if parser.is_metafunc(func):
                parser.metafunc(spy)

            bot.parse_direct_message({
                'user': MOCK_PERSON,
                'channel': MOCK_CHANNEL,
                'text': message_text
            })

            assert spy.call_count == 1
            expected_func_names.append(func.__name__)

        second_bot = TodayIDidBot('', command_history_file=bot.command_history_file, reports_dir=bot.reports_dir)
        saved_func_names = [command['action'].__name__
                          for command in second_bot.command_history.history[MOCK_CHANNEL]]
        assert saved_func_names == expected_func_names