Python inspect.Parameter.VAR_KEYWORD Examples

The following are 12 code examples of inspect.Parameter.VAR_KEYWORD(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect.Parameter , or try the search function .
Example #1
Source File: model.py    From Seq2Seq-Tensorflow with MIT License 7 votes vote down vote up
def auto_assign(func):
    # Signature:
    sig = signature(func)
    for name, param in sig.parameters.items():
        if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
            raise RuntimeError('Unable to auto assign if *args or **kwargs in signature.')
    # Wrapper:
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        for i, (name, param) in enumerate(sig.parameters.items()):
            # Skip 'self' param:
            if i == 0: continue
            # Search value in args, kwargs or defaults:
            if i - 1 < len(args):
                val = args[i - 1]
            elif name in kwargs:
                val = kwargs[name]
            else:
                val = param.default
            setattr(self, name, val)
        func(self, *args, **kwargs)
    return wrapper 
Example #2
Source File: interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def _yield_abbreviations_for_parameter(param, kwargs):
    """Get an abbreviation for a function parameter."""
    name = param.name
    kind = param.kind
    ann = param.annotation
    default = param.default
    not_found = (name, empty, empty)
    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
        if name in kwargs:
            value = kwargs.pop(name)
        elif ann is not empty:
            warn("Using function annotations to implicitly specify interactive controls is deprecated. Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
            value = ann
        elif default is not empty:
            value = default
        else:
            yield not_found
        yield (name, value, default)
    elif kind == Parameter.VAR_KEYWORD:
        # In this case name=kwargs and we yield the items in kwargs with their keys.
        for k, v in kwargs.copy().items():
            kwargs.pop(k)
            yield k, v, empty 
Example #3
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _yield_abbreviations_for_parameter(param, kwargs):
    """Get an abbreviation for a function parameter."""
    name = param.name
    kind = param.kind
    ann = param.annotation
    default = param.default
    not_found = (name, empty, empty)
    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
        if name in kwargs:
            value = kwargs.pop(name)
        elif ann is not empty:
            warn("Using function annotations to implicitly specify interactive controls is deprecated. Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
            value = ann
        elif default is not empty:
            value = default
        else:
            yield not_found
        yield (name, value, default)
    elif kind == Parameter.VAR_KEYWORD:
        # In this case name=kwargs and we yield the items in kwargs with their keys.
        for k, v in kwargs.copy().items():
            kwargs.pop(k)
            yield k, v, empty 
Example #4
Source File: compat.py    From easy_cache with MIT License 6 votes vote down vote up
def getargspec(func):
        signature = inspect.signature(func)

        args = []
        varargs = None
        keywords = None
        defaults = []

        for param in signature.parameters.values():  # type: Parameter
            if param.kind == Parameter.VAR_POSITIONAL:
                varargs = param.name
            elif param.kind in (
                    Parameter.POSITIONAL_ONLY,
                    Parameter.KEYWORD_ONLY,
                    Parameter.POSITIONAL_OR_KEYWORD):
                args.append(param.name)
            elif param.kind == Parameter.VAR_KEYWORD:
                keywords = param.name

            # noinspection PyProtectedMember
            if param.default is not inspect._empty:
                defaults.append(param.default)

        return ArgSpec(args, varargs, keywords, tuple(defaults)) 
Example #5
Source File: sequence.py    From chainerrl with MIT License 5 votes vote down vote up
def accept_variable_arguments(func):
    for param in signature(func).parameters.values():
        if param.kind in (Parameter.VAR_POSITIONAL,
                          Parameter.VAR_KEYWORD):
            return True
    return False 
Example #6
Source File: signature.py    From sacred with MIT License 5 votes vote down vote up
def get_argspec(f):
    sig = inspect.signature(f)
    args = [n for n, p in sig.parameters.items() if p.kind in ARG_TYPES]
    pos_args = [
        n
        for n, p in sig.parameters.items()
        if p.kind in POSARG_TYPES and p.default == inspect._empty
    ]
    varargs = [
        n for n, p in sig.parameters.items() if p.kind == Parameter.VAR_POSITIONAL
    ]
    # only use first vararg  (how on earth would you have more anyways?)
    vararg_name = varargs[0] if varargs else None

    varkws = [n for n, p in sig.parameters.items() if p.kind == Parameter.VAR_KEYWORD]
    # only use first varkw  (how on earth would you have more anyways?)
    kw_wildcard_name = varkws[0] if varkws else None
    kwargs = OrderedDict(
        [
            (n, p.default)
            for n, p in sig.parameters.items()
            if p.default != inspect._empty
        ]
    )

    return args, vararg_name, kw_wildcard_name, pos_args, kwargs 
Example #7
Source File: signature.py    From mockito-python with MIT License 5 votes vote down vote up
def has_var_keyword(sig):
    return any(p for n, p in sig.parameters.items()
               if p.kind is Parameter.VAR_KEYWORD) 
Example #8
Source File: signature.py    From ray with Apache License 2.0 5 votes vote down vote up
def _convert_from_parameter_kind(kind):
    if kind == Parameter.POSITIONAL_ONLY:
        return 0
    if kind == Parameter.POSITIONAL_OR_KEYWORD:
        return 1
    if kind == Parameter.VAR_POSITIONAL:
        return 2
    if kind == Parameter.KEYWORD_ONLY:
        return 3
    if kind == Parameter.VAR_KEYWORD:
        return 4 
Example #9
Source File: test_viewable.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_viewable_signature(viewable):
    from inspect import Parameter, signature
    parameters = signature(viewable).parameters
    assert 'params' in parameters
    assert parameters['params'] == Parameter('params', Parameter.VAR_KEYWORD) 
Example #10
Source File: interact.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _yield_abbreviations_for_parameter(parameter, kwargs):
    """Get an abbreviation for a function parameter."""
    name = parameter.name
    kind = parameter.kind
    ann = parameter.annotation
    default = parameter.default
    not_found = (name, empty, empty)
    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
        if name in kwargs:
            value = kwargs.pop(name)
        elif ann is not empty:
            param.main.warning("Using function annotations to implicitly specify interactive controls is deprecated. "
                               "Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
            value = ann
        elif default is not empty:
            value = default
            if isinstance(value, (Iterable, Mapping)):
                value = fixed(value)
        else:
            yield not_found
        yield (name, value, default)
    elif kind == Parameter.VAR_KEYWORD:
        # In this case name=kwargs and we yield the items in kwargs with their keys.
        for k, v in kwargs.copy().items():
            kwargs.pop(k)
            yield k, v, empty 
Example #11
Source File: config.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _apply_signatures(self):
        from inspect import Parameter, Signature
        from .viewable import Viewable

        descendants = param.concrete_descendents(Viewable)
        for cls in reversed(list(descendants.values())):
            if cls.__doc__.startswith('params'):
                prefix = cls.__doc__.split('\n')[0]
                cls.__doc__ = cls.__doc__.replace(prefix, '')
            sig = inspect.signature(cls.__init__)
            sig_params = list(sig.parameters.values())
            if not sig_params or sig_params[-1] != Parameter('params', Parameter.VAR_KEYWORD):
                continue
            parameters = sig_params[:-1]

            processed_kws, keyword_groups = set(), []
            for cls in reversed(cls.mro()):
                keyword_group = []
                for (k, v) in sorted(cls.__dict__.items()):
                    if (isinstance(v, param.Parameter) and k not in processed_kws
                        and not v.readonly):
                        keyword_group.append(k)
                        processed_kws.add(k)
                keyword_groups.append(keyword_group)

            parameters += [
                Parameter(name, Parameter.KEYWORD_ONLY)
                for kws in reversed(keyword_groups) for name in kws
                if name not in sig.parameters
            ]
            parameters.append(Parameter('kwargs', Parameter.VAR_KEYWORD))
            cls.__init__.__signature__ = Signature(
                parameters, return_annotation=sig.return_annotation
            )


#---------------------------------------------------------------------
# Private API
#--------------------------------------------------------------------- 
Example #12
Source File: utils.py    From pydantic with MIT License 4 votes vote down vote up
def generate_model_signature(
    init: Callable[..., None], fields: Dict[str, 'ModelField'], config: Type['BaseConfig']
) -> 'Signature':
    """
    Generate signature for model based on its fields
    """
    from inspect import Parameter, Signature, signature

    present_params = signature(init).parameters.values()
    merged_params: Dict[str, Parameter] = {}
    var_kw = None
    use_var_kw = False

    for param in islice(present_params, 1, None):  # skip self arg
        if param.kind is param.VAR_KEYWORD:
            var_kw = param
            continue
        merged_params[param.name] = param

    if var_kw:  # if custom init has no var_kw, fields which are not declared in it cannot be passed through
        allow_names = config.allow_population_by_field_name
        for field_name, field in fields.items():
            param_name = field.alias
            if field_name in merged_params or param_name in merged_params:
                continue
            elif not param_name.isidentifier():
                if allow_names and field_name.isidentifier():
                    param_name = field_name
                else:
                    use_var_kw = True
                    continue

            # TODO: replace annotation with actual expected types once #1055 solved
            kwargs = {'default': field.default} if not field.required else {}
            merged_params[param_name] = Parameter(
                param_name, Parameter.KEYWORD_ONLY, annotation=field.outer_type_, **kwargs
            )

    if config.extra is config.extra.allow:
        use_var_kw = True

    if var_kw and use_var_kw:
        # Make sure the parameter for extra kwargs
        # does not have the same name as a field
        default_model_signature = [
            ('__pydantic_self__', Parameter.POSITIONAL_OR_KEYWORD),
            ('data', Parameter.VAR_KEYWORD),
        ]
        if [(p.name, p.kind) for p in present_params] == default_model_signature:
            # if this is the standard model signature, use extra_data as the extra args name
            var_kw_name = 'extra_data'
        else:
            # else start from var_kw
            var_kw_name = var_kw.name

        # generate a name that's definitely unique
        while var_kw_name in fields:
            var_kw_name += '_'
        merged_params[var_kw_name] = var_kw.replace(name=var_kw_name)

    return Signature(parameters=list(merged_params.values()), return_annotation=None)