Python inspect.Parameter.empty() Examples

The following are 30 code examples of inspect.Parameter.empty(). 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: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_abbreviations(self, kwargs):
        """Find the abbreviations for the given function and kwargs.
        Return (name, abbrev, default) tuples.
        """
        new_kwargs = []
        try:
            sig = self.signature()
        except (ValueError, TypeError):
            # can't inspect, no info from function; only use kwargs
            return [ (key, value, value) for key, value in kwargs.items() ]

        for param in sig.parameters.values():
            for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
                if value is empty:
                    raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
                new_kwargs.append((name, value, default))
        return new_kwargs

    # Abbreviations to widgets 
Example #2
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 #3
Source File: base.py    From gs-quant with Apache License 2.0 6 votes vote down vote up
def _from_dict(cls, values: dict) -> 'Base':
        args = [k for k, v in signature(cls.__init__).parameters.items() if k not in ('kwargs', '_kwargs')
                and v.default == Parameter.empty][1:]
        required = {}

        for arg in args:
            prop_name = arg[:-1] if arg.endswith('_') and not keyword.iskeyword(arg) else arg
            prop_type = cls.prop_type(prop_name)
            value = values.pop(arg, None)

            if prop_type:
                if issubclass(prop_type, Base) and isinstance(value, dict):
                    value = prop_type.from_dict(value)
                elif issubclass(prop_type, (list, tuple)) and isinstance(value, (list, tuple)):
                    item_type = cls.prop_item_type(prop_name)
                    if issubclass(item_type, Base):
                        value = tuple(v if isinstance(v, (Base, EnumBase)) else item_type.from_dict(v) for v in value)
                elif issubclass(prop_type, EnumBase):
                    value = get_enum_value(prop_type, value)

            required[arg] = value

        instance = cls(**required)
        instance.__from_dict(values)
        return instance 
Example #4
Source File: validate.py    From ibis with Apache License 2.0 6 votes vote down vote up
def _parameter_count(funcsig: signature) -> int:
    """Get the number of positional-or-keyword or position-only parameters in a
    function signature.

    Parameters
    ----------
    funcsig : inspect.Signature
        A UDF signature

    Returns
    -------
    int
        The number of parameters
    """
    return sum(
        param.kind in {param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY}
        for param in funcsig.parameters.values()
        if param.default is Parameter.empty
    ) 
Example #5
Source File: interact.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_abbreviations(self, kwargs):
        """Find the abbreviations for the given function and kwargs.
        Return (name, abbrev, default) tuples.
        """
        new_kwargs = []
        try:
            sig = self.signature()
        except (ValueError, TypeError):
            # can't inspect, no info from function; only use kwargs
            return [ (key, value, value) for key, value in kwargs.items() ]

        for parameter in sig.parameters.values():
            for name, value, default in _yield_abbreviations_for_parameter(parameter, kwargs):
                if value is empty:
                    raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
                new_kwargs.append((name, value, default))
        return new_kwargs 
Example #6
Source File: gate_utils.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def _get_free_params(fun, ignore=None):
    """Get the names of the free parameters of the function ``f``.

    Args:
        fun (callable): The function to inspect.
        ignore (list[str]): A list of argument names (as str) to ignore.

    Returns:
        list[str]: The name of the free parameters not listed in ``ignore``.
    """
    ignore = ignore or []
    free_params = []
    for name, param in signature(fun).parameters.items():
        if param.default == Parameter.empty and param.kind != Parameter.VAR_POSITIONAL:
            if name not in ignore:
                free_params.append(name)
    return free_params 
Example #7
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 #8
Source File: interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def find_abbreviations(self, kwargs):
        """Find the abbreviations for the given function and kwargs.
        Return (name, abbrev, default) tuples.
        """
        new_kwargs = []
        try:
            sig = self.signature()
        except (ValueError, TypeError):
            # can't inspect, no info from function; only use kwargs
            return [ (key, value, value) for key, value in kwargs.items() ]

        for param in sig.parameters.values():
            for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
                if value is empty:
                    raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
                new_kwargs.append((name, value, default))
        return new_kwargs

    # Abbreviations to widgets 
Example #9
Source File: configuration.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_param_annotation(p):
    # if not annotated, infer type from default
    if p.annotation == Parameter.empty and p.default == Parameter.empty:
        raise ValueError(
            f"Param {p}: both annotation and default are empty, "
            "so cannot infer any useful annotation."
        )
    if p.annotation != Parameter.empty:
        return p.annotation
    # case on default types
    if p.default is None:
        raise ValueError(
            f"Param {p}: default is None and annotation is empty, "
            "cannot infer useful annotation"
        )
    if isinstance(p.default, tuple):
        raise ValueError(f"Param {p}: default is tuple, cannot infer type")
    if isinstance(p.default, dict):
        raise ValueError(f"Param{p}: default is tuple, cannot infer type")
    return type(p.default) 
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_parser.py    From TopicNet with MIT License 5 votes vote down vote up
def choose_key(param):
    """
    Parameters
    ----------
    param : inspect.Parameter

    Returns
    -------
    str or strictyaml.Optional
    """
    if param.default is not Parameter.empty:
        return Optional(param.name)
    return param.name 
Example #12
Source File: interact.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def widget_from_abbrev(cls, abbrev, name, default=empty):
        """Build a ValueWidget instance given an abbreviation or Widget."""
        if isinstance(abbrev, Widget):
            return abbrev

        if isinstance(abbrev, tuple):
            widget = cls.widget_from_tuple(abbrev, name, default)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # Try single value
        widget = cls.widget_from_single_value(abbrev, name)
        if widget is not None:
            return widget

        # Something iterable (list, dict, generator, ...). Note that str and
        # tuple should be handled before, that is why we check this case last.
        if isinstance(abbrev, Iterable):
            widget = cls.widget_from_iterable(abbrev, name)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # No idea...
        return fixed(abbrev) 
Example #13
Source File: interact.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def widget_from_tuple(o, name, default=empty):
        """Make widgets from a tuple abbreviation."""
        int_default = (default is empty or isinstance(default, int))
        if _matches(o, (Real, Real)):
            min, max, value = _get_min_max_value(o[0], o[1])
            if all(isinstance(_, Integral) for _ in o) and int_default:
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, start=min, end=max, name=name)
        elif _matches(o, (Real, Real, Real)):
            step = o[2]
            if step <= 0:
                raise ValueError("step must be >= 0, not %r" % step)
            min, max, value = _get_min_max_value(o[0], o[1], step=step)
            if all(isinstance(_, Integral) for _ in o) and int_default:
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, start=min, end=max, step=step, name=name)
        elif _matches(o, (Real, Real, Real, Real)):
            step = o[2]
            if step <= 0:
                raise ValueError("step must be >= 0, not %r" % step)
            min, max, value = _get_min_max_value(o[0], o[1], value=o[3], step=step)
            if all(isinstance(_, Integral) for _ in o):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, start=min, end=max, step=step, name=name)
        elif len(o) == 4:
            min, max, value = _get_min_max_value(o[0], o[1], value=o[3])
            if all(isinstance(_, Integral) for _ in [o[0], o[1], o[3]]):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, start=min, end=max, name=name) 
Example #14
Source File: typed_struct.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_parameter(self):
        from inspect import Parameter

        return Parameter(
            name=self.name,
            kind=Parameter.KEYWORD_ONLY,
            default=Parameter.empty if self.default is MANDATORY else self.default,
            annotation=self.type) 
Example #15
Source File: app.py    From chi with MIT License 5 votes vote down vote up
def parse_args_and_run(self, args=None):
    args = args or sys.argv
    import argparse
    parser = argparse.ArgumentParser(description=self.f.__name__)

    for n, p in self.params.items():
      d = p.default == Parameter.empty
      t = str if d else type(p.default)
      if t is bool:
        g = parser.add_mutually_exclusive_group(required=False)
        g.add_argument('--' + n, dest=n, action='store_true')
        g.add_argument('--no-' + n, dest=n, action='store_false')
        parser.set_defaults(**{n: Parameter.empty})
      elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
        g = parser.add_mutually_exclusive_group(required=d)
        g.add_argument(n, nargs='?', type=t, default=Parameter.empty)
        g.add_argument('--' + n, dest='--' + n, type=t, default=Parameter.empty, help=argparse.SUPPRESS)
      elif p.kind == Parameter.KEYWORD_ONLY:
        parser.add_argument('--' + n, type=type(p.default), default=p.default)

    ag = vars(parser.parse_args())
    parsed = {}
    for n, p in self.params.items():
      a, b, c = ag[n], ag.get('--' + n, Parameter.empty), p.default
      v = a if a != Parameter.empty else b if b != Parameter.empty else c
      parsed.update({n: v})

    result = self.run(**parsed)

    from chi.logger import logger
    logger.info('Finishing with ' + str(result))

    sys.exit(result) 
Example #16
Source File: bash.py    From parsl with Apache License 2.0 5 votes vote down vote up
def __init__(self, func, data_flow_kernel=None, cache=False, executors='all', ignore_for_cache=None):
        super().__init__(func, data_flow_kernel=data_flow_kernel, executors=executors, cache=cache, ignore_for_cache=ignore_for_cache)
        self.kwargs = {}

        # We duplicate the extraction of parameter defaults
        # to self.kwargs to ensure availability at point of
        # command string format. Refer: #349
        sig = signature(func)

        for s in sig.parameters:
            if sig.parameters[s].default is not Parameter.empty:
                self.kwargs[s] = sig.parameters[s].default 
Example #17
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def widget_from_abbrev(cls, abbrev, default=empty):
        """Build a ValueWidget instance given an abbreviation or Widget."""
        if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
            return abbrev

        if isinstance(abbrev, tuple):
            widget = cls.widget_from_tuple(abbrev)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # Try single value
        widget = cls.widget_from_single_value(abbrev)
        if widget is not None:
            return widget

        # Something iterable (list, dict, generator, ...). Note that str and
        # tuple should be handled before, that is why we check this case last.
        if isinstance(abbrev, Iterable):
            widget = cls.widget_from_iterable(abbrev)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # No idea...
        return None 
Example #18
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def default_instance(cls):
        """
        Construct a default instance of this type
        """
        args = [k for k, v in signature(cls.__init__).parameters.items() if v.default == Parameter.empty][1:]
        required = {a: None for a in args}
        return cls(**required) 
Example #19
Source File: _dynamic.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, default=Parameter.empty, annotation=Parameter.empty):
        super().__init__(name, Parameter.POSITIONAL_OR_KEYWORD, default=default, annotation=annotation) 
Example #20
Source File: interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def widget_from_abbrev(cls, abbrev, default=empty):
        """Build a ValueWidget instance given an abbreviation or Widget."""
        if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
            return abbrev

        if isinstance(abbrev, tuple):
            widget = cls.widget_from_tuple(abbrev)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # Try single value
        widget = cls.widget_from_single_value(abbrev)
        if widget is not None:
            return widget

        # Something iterable (list, dict, generator, ...). Note that str and
        # tuple should be handled before, that is why we check this case last.
        if isinstance(abbrev, Iterable):
            widget = cls.widget_from_iterable(abbrev)
            if default is not empty:
                try:
                    widget.value = default
                except Exception:
                    # ignore failure to set default
                    pass
            return widget

        # No idea...
        return None 
Example #21
Source File: compat.py    From pytest with MIT License 5 votes vote down vote up
def get_default_arg_names(function: Callable[..., Any]) -> Tuple[str, ...]:
    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
    # to get the arguments which were excluded from its result because they had default values
    return tuple(
        p.name
        for p in signature(function).parameters.values()
        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
        and p.default is not Parameter.empty
    ) 
Example #22
Source File: compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def get_default_arg_names(function):
    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
    # to get the arguments which were excluded from its result because they had default values
    return tuple(
        p.name
        for p in signature(function).parameters.values()
        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
        and p.default is not Parameter.empty
    ) 
Example #23
Source File: compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def get_default_arg_names(function):
    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
    # to get the arguments which were excluded from its result because they had default values
    return tuple(
        p.name
        for p in signature(function).parameters.values()
        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
        and p.default is not Parameter.empty
    ) 
Example #24
Source File: _dynamic.py    From pipelines with Apache License 2.0 4 votes vote down vote up
def create_function_from_parameters(func: Callable[[Mapping[str, Any]], Any], parameters: Sequence[Parameter], documentation=None, func_name=None, func_filename=None):
    new_signature = Signature(parameters) # Checks the parameter consistency

    def pass_locals():
        return dict_func(locals())  # noqa: F821 TODO

    code = pass_locals.__code__
    mod_co_argcount = len(parameters)
    mod_co_nlocals = len(parameters)
    mod_co_varnames = tuple(param.name for param in parameters)
    mod_co_name = func_name or code.co_name
    if func_filename:
        mod_co_filename = func_filename
        mod_co_firstlineno = 1
    else:
        mod_co_filename = code.co_filename
        mod_co_firstlineno = code.co_firstlineno

    if sys.version_info >= (3, 8):
        modified_code = code.replace(
            co_argcount=mod_co_argcount,
            co_nlocals=mod_co_nlocals,
            co_varnames=mod_co_varnames,
            co_filename=mod_co_filename,
            co_name=mod_co_name,
            co_firstlineno=mod_co_firstlineno,
        )
    else:
        modified_code = types.CodeType(
            mod_co_argcount,
            code.co_kwonlyargcount,
            mod_co_nlocals,
            code.co_stacksize,
            code.co_flags,
            code.co_code,
            code.co_consts,
            code.co_names,
            mod_co_varnames,
            mod_co_filename,
            mod_co_name,
            mod_co_firstlineno,
            code.co_lnotab
        )

    default_arg_values = tuple( p.default for p in parameters if p.default != Parameter.empty ) #!argdefs "starts from the right"/"is right-aligned"
    modified_func = types.FunctionType(modified_code, {'dict_func': func, 'locals': locals}, name=func_name, argdefs=default_arg_values)
    modified_func.__doc__ = documentation
    modified_func.__signature__ = new_signature

    return modified_func 
Example #25
Source File: __init__.py    From dagster with Apache License 2.0 4 votes vote down vote up
def _check_serdes_tuple_class_invariants(klass):
    check.invariant(sys.version_info.major >= 3, 'This function can only be run in python 3')

    # pull this in dynamically because this method is only called in python 3 contexts
    from inspect import Parameter

    dunder_new_params = _get_dunder_new_params(klass)

    cls_param = dunder_new_params[0]

    def _with_header(msg):
        return 'For namedtuple {class_name}: {msg}'.format(class_name=klass.__name__, msg=msg)

    if cls_param.name not in {'cls', '_cls'}:
        raise SerdesClassUsageError(
            _with_header(
                'First parameter must be _cls or cls. Got "{name}".'.format(name=cls_param.name)
            )
        )

    value_params = dunder_new_params[1:]

    for index, field in enumerate(klass._fields):

        if index >= len(value_params):
            error_msg = (
                'Missing parameters to __new__. You have declared fields '
                'in the named tuple that are not present as parameters to the '
                'to the __new__ method. In order for '
                'both serdes serialization and pickling to work, '
                'these must match. Missing: {missing_fields}'
            ).format(missing_fields=repr(list(klass._fields[index:])))

            raise SerdesClassUsageError(_with_header(error_msg))

        value_param = value_params[index]
        if value_param.name != field:
            error_msg = (
                'Params to __new__ must match the order of field declaration in the namedtuple. '
                'Declared field number {one_based_index} in the namedtuple is "{field_name}". '
                'Parameter {one_based_index} in __new__ method is "{param_name}".'
            ).format(one_based_index=index + 1, field_name=field, param_name=value_param.name)
            raise SerdesClassUsageError(_with_header(error_msg))

    if len(value_params) > len(klass._fields):
        # Ensure that remaining parameters have default values
        for extra_param_index in range(len(klass._fields), len(value_params) - 1):
            if value_params[extra_param_index].default == Parameter.empty:
                error_msg = (
                    'Parameter "{param_name}" is a parameter to the __new__ '
                    'method but is not a field in this namedtuple. The only '
                    'reason why this should exist is that '
                    'it is a field that used to exist (we refer to this as the graveyard) '
                    'but no longer does. However it might exist in historical storage. This '
                    'parameter existing ensures that serdes continues to work. However these '
                    'must come at the end and have a default value for pickling to work.'
                ).format(param_name=value_params[extra_param_index].name)
                raise SerdesClassUsageError(_with_header(error_msg)) 
Example #26
Source File: debug.py    From PyDMXControl with GNU General Public License v3.0 4 votes vote down vote up
def __callbacks_parameters(parameters: List[Parameter]) -> Tuple[list, dict]:
        # Given params
        ordered_params = []
        keyword_params = {}

        # Go through all params
        for param in parameters:
            # Basic param information
            has_default = (param.default != Parameter.empty)
            has_type = (param.annotation != Parameter.empty)
            param_type = str(param.annotation) if has_type else "Unknown"
            param_default = (", leave blank for default " + str(param.default)) if has_default else ""

            # Validate the parameter input
            given_param = False

            def valid(this):
                # Not started
                if this is None:
                    return False

                # Default?
                if this.strip() == "":
                    if has_default:
                        return param.default
                    return False

                # Normal
                try:
                    return param.annotation(this)
                except Exception:
                    return this

            # Get input
            while given_param is False:
                given_param = valid(input(
                    "[Callbacks Debug] Parameter '" + param.name + "' (expects " + param_type + param_default + "): "))

            # Add to return
            if param.kind == Parameter.POSITIONAL_ONLY:
                ordered_params.append(given_param)
            else:
                keyword_params[param.name] = given_param

        return ordered_params, keyword_params 
Example #27
Source File: compat.py    From pytest with MIT License 4 votes vote down vote up
def getfuncargnames(
    function: Callable[..., Any],
    *,
    name: str = "",
    is_method: bool = False,
    cls: Optional[type] = None
) -> Tuple[str, ...]:
    """Returns the names of a function's mandatory arguments.

    This should return the names of all function arguments that:
        * Aren't bound to an instance or type as in instance or class methods.
        * Don't have default values.
        * Aren't bound with functools.partial.
        * Aren't replaced with mocks.

    The is_method and cls arguments indicate that the function should
    be treated as a bound method even though it's not unless, only in
    the case of cls, the function is a static method.

    The name parameter should be the original name in which the function was collected.
    """
    # TODO(RonnyPfannschmidt): This function should be refactored when we
    # revisit fixtures. The fixture mechanism should ask the node for
    # the fixture names, and not try to obtain directly from the
    # function object well after collection has occurred.

    # The parameters attribute of a Signature object contains an
    # ordered mapping of parameter names to Parameter instances.  This
    # creates a tuple of the names of the parameters that don't have
    # defaults.
    try:
        parameters = signature(function).parameters
    except (ValueError, TypeError) as e:
        fail(
            "Could not determine arguments of {!r}: {}".format(function, e),
            pytrace=False,
        )

    arg_names = tuple(
        p.name
        for p in parameters.values()
        if (
            p.kind is Parameter.POSITIONAL_OR_KEYWORD
            or p.kind is Parameter.KEYWORD_ONLY
        )
        and p.default is Parameter.empty
    )
    if not name:
        name = function.__name__

    # If this function should be treated as a bound method even though
    # it's passed as an unbound method or function, remove the first
    # parameter name.
    if is_method or (
        cls and not isinstance(cls.__dict__.get(name, None), staticmethod)
    ):
        arg_names = arg_names[1:]
    # Remove any names that will be replaced with mocks.
    if hasattr(function, "__wrapped__"):
        arg_names = arg_names[num_mock_patch_args(function) :]
    return arg_names 
Example #28
Source File: cli.py    From halocoin with Apache License 2.0 4 votes vote down vote up
def run(argv):
    parser = argparse.ArgumentParser(description='CLI for halocoin.')
    parser.add_argument('action', choices=sorted(actions.keys()),
                        help="Main action to perform by this CLI.")
    parser.add_argument('--version', action='version', version='%(prog)s ' + custom.version)
    parser.add_argument('--address', action="store", type=str, dest='address',
                        help='Give a valid blockchain address')
    parser.add_argument('--message', action="store", type=str, dest='message',
                        help='Message to send with transaction')
    parser.add_argument('--amount', action="store", type=int, dest='amount',
                        help='Amount of coins that are going to be used')
    parser.add_argument('--start', metavar='<integer>', action="store", type=str, dest='start',
                        help='Starting number while requesting range of blocks')
    parser.add_argument('--end', metavar='<integer>', action="store", type=str, dest='end',
                        help='Ending number while requesting range of blocks')
    parser.add_argument('--file', metavar='/file/path', action="store", type=str, dest='file',
                        help='File path for wallet upload')
    parser.add_argument('--wallet', metavar='my_wallet', action="store", type=str, dest='wallet',
                        help='Wallet name')
    parser.add_argument('--config', action="store", type=str, dest='config',
                        help='Config file address. Use with start command.')
    parser.add_argument('--pw', action="store", type=str, dest='pw',
                        help='NOT RECOMMENDED! If you want to pass wallet password as argument.')
    parser.add_argument('--dir', action="store", type=str, dest='dir',
                        help='Directory for halocoin to use.')
    parser.add_argument('--port', action="store", type=int, dest='port',
                        help='Override API port defined in config file.')
    parser.add_argument('--force', action="store_true", dest='force',
                        help='Force something that makes trouble.')

    args = parser.parse_args(argv[1:])

    config, working_dir = extract_configuration(args.dir, args.config)
    global connection_port
    connection_port = config['port']['api']

    from inspect import signature
    sig = signature(actions[args.action])
    kwargs = {}
    for parameter in sig.parameters.keys():
        if sig.parameters[parameter].default == Parameter.empty and \
                (not hasattr(args, parameter) or getattr(args, parameter) is None):
            sys.stderr.write("\"{}\" requires parameter {}\n".format(args.action, parameter))
            sys.exit(1)
        kwargs[parameter] = getattr(args, parameter)
    actions[args.action](**kwargs)
    return 
Example #29
Source File: compat.py    From python-netsurv with MIT License 4 votes vote down vote up
def getfuncargnames(function, is_method=False, cls=None):
    """Returns the names of a function's mandatory arguments.

    This should return the names of all function arguments that:
        * Aren't bound to an instance or type as in instance or class methods.
        * Don't have default values.
        * Aren't bound with functools.partial.
        * Aren't replaced with mocks.

    The is_method and cls arguments indicate that the function should
    be treated as a bound method even though it's not unless, only in
    the case of cls, the function is a static method.

    @RonnyPfannschmidt: This function should be refactored when we
    revisit fixtures. The fixture mechanism should ask the node for
    the fixture names, and not try to obtain directly from the
    function object well after collection has occurred.

    """
    # The parameters attribute of a Signature object contains an
    # ordered mapping of parameter names to Parameter instances.  This
    # creates a tuple of the names of the parameters that don't have
    # defaults.
    try:
        parameters = signature(function).parameters
    except (ValueError, TypeError) as e:
        fail(
            "Could not determine arguments of {!r}: {}".format(function, e),
            pytrace=False,
        )

    arg_names = tuple(
        p.name
        for p in parameters.values()
        if (
            p.kind is Parameter.POSITIONAL_OR_KEYWORD
            or p.kind is Parameter.KEYWORD_ONLY
        )
        and p.default is Parameter.empty
    )
    # If this function should be treated as a bound method even though
    # it's passed as an unbound method or function, remove the first
    # parameter name.
    if is_method or (
        cls and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)
    ):
        arg_names = arg_names[1:]
    # Remove any names that will be replaced with mocks.
    if hasattr(function, "__wrapped__"):
        arg_names = arg_names[num_mock_patch_args(function) :]
    return arg_names 
Example #30
Source File: compat.py    From python-netsurv with MIT License 4 votes vote down vote up
def getfuncargnames(function, is_method=False, cls=None):
    """Returns the names of a function's mandatory arguments.

    This should return the names of all function arguments that:
        * Aren't bound to an instance or type as in instance or class methods.
        * Don't have default values.
        * Aren't bound with functools.partial.
        * Aren't replaced with mocks.

    The is_method and cls arguments indicate that the function should
    be treated as a bound method even though it's not unless, only in
    the case of cls, the function is a static method.

    @RonnyPfannschmidt: This function should be refactored when we
    revisit fixtures. The fixture mechanism should ask the node for
    the fixture names, and not try to obtain directly from the
    function object well after collection has occurred.

    """
    # The parameters attribute of a Signature object contains an
    # ordered mapping of parameter names to Parameter instances.  This
    # creates a tuple of the names of the parameters that don't have
    # defaults.
    try:
        parameters = signature(function).parameters
    except (ValueError, TypeError) as e:
        fail(
            "Could not determine arguments of {!r}: {}".format(function, e),
            pytrace=False,
        )

    arg_names = tuple(
        p.name
        for p in parameters.values()
        if (
            p.kind is Parameter.POSITIONAL_OR_KEYWORD
            or p.kind is Parameter.KEYWORD_ONLY
        )
        and p.default is Parameter.empty
    )
    # If this function should be treated as a bound method even though
    # it's passed as an unbound method or function, remove the first
    # parameter name.
    if is_method or (
        cls and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)
    ):
        arg_names = arg_names[1:]
    # Remove any names that will be replaced with mocks.
    if hasattr(function, "__wrapped__"):
        arg_names = arg_names[num_mock_patch_args(function) :]
    return arg_names