Return an appropriate Expression given the arguments

    Parameters
    ----------
    args : tuple
        Positional arguments passed to the Expression class
    kwargs : dict
        Keyword arguments passed to the Expression class
769636
def Expression(*args, **kwargs):
    
    # dispatch
    if not hasattr(args[0], '_Expression'):
        return BaseExpression(*args, *kwargs)
    else:
        return args[0]._Expression(*args, **kwargs)
108635
def args_str(self):
        
        matched = [str(m) for m in self._matchers[:self._position]]
        unmatched = [str(m) for m in self._matchers[self._position:]]
        return 'matched=[{}], unmatched=[{}]'.format(
            ', '.join(matched), ', '.join(unmatched))
291993
def args(self):  # as args tuple
        '''
        '''
        return (self.base, self.item, self.leng, self.refs,
                self.both, self.kind, self.type)
340196
def format_args(self):
        
        result = []
        if self.args:
            result.append(
                _format_args(
                    self.args, self.defaults, getattr(self, "annotations", None)
                )
            )
        if self.vararg:
            result.append("*%s" % self.vararg)
        if self.kwonlyargs:
            if not self.vararg:
                result.append("*")
            result.append(
                _format_args(
                    self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations
                )
            )
        if self.kwarg:
            result.append("**%s" % self.kwarg)
        return ", ".join(result)
87066
def parse_argument_list(self):
        
        # Try to parse a subexpression in a subparser.
        expressions = []

        while self.pos < len(self.string):
            subparser = Parser(self.string[self.pos:], in_argument=True)
            subparser.parse_expression()

            # Extract and advance past the parsed expression.
            expressions.append(Expression(subparser.parts))
            self.pos += subparser.pos

            if self.pos >= len(self.string) or \
               self.string[self.pos] == GROUP_CLOSE:
                # Argument list terminated by EOF or closing brace.
                break

            # Only other way to terminate an expression is with ,.
            # Continue to the next argument.
            assert self.string[self.pos] == ARG_SEP
            self.pos += 1

        return expressions
1215155
def _parse_index_value(self, kwargs):
        
        if len(kwargs) == 0:
            return None, None
        elif len(kwargs) > 1:
            raise ValueError("You can't pass more than one value expression, "
                             "you passed {}".format(",".join(kwargs.keys())))

        name, value = list(kwargs.items())[0]

        if not name.startswith('value'):
            raise ValueError("The keyword arg {} is not valid for this "
                             "function".format(name))

        if name == 'value':
            return ('=', value)

        if not name.startswith('value__'):
            raise ValueError("The keyword arg {} is not valid for this "
                             "function".format(name))

        operator = name[name.find('__') + 2:]
        try:
            return (self._operator_values[operator], value)
        except KeyError:
            raise ValueError(
                "The operator {op} is not valid for index value matching. "
                "Valid operators are {valid}"
                .format(
                    op=operator,
                    valid=",".join(self._operator_values.keys()),
                ),
            )
503947
def bind(self, args, kwargs):
        
        spec = self._spec
        resolution = self.resolve(args, kwargs)
        params = dict(zip(spec.args, resolution.slots))
        if spec.varargs:
            params[spec.varargs] = resolution.varargs
        if spec.varkw:
            params[spec.varkw] = resolution.varkw
        if spec.kwonlyargs:
            params.update(resolution.kwonlyargs)
        return params
25823
def use_args(
        self,
        argmap: ArgMap,
        req: typing.Optional[Request] = None,
        locations: typing.Iterable = None,
        as_kwargs: bool = False,
        validate: Validate = None,
        error_status_code: typing.Optional[int] = None,
        error_headers: typing.Union[typing.Mapping[str, str], None] = None,
    ) -> typing.Callable[..., typing.Callable]:
        
        locations = locations or self.locations
        request_obj = req
        # Optimization: If argmap is passed as a dictionary, we only need
        # to generate a Schema once
        if isinstance(argmap, Mapping):
            argmap = core.dict2schema(argmap, self.schema_class)()

        def decorator(func: typing.Callable) -> typing.Callable:
            req_ = request_obj

            if inspect.iscoroutinefunction(func):

                @functools.wraps(func)
                async def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = await self.parse(
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args or {})
                        return await func(*args, **kwargs)
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return await func(*new_args, **kwargs)

            else:

                @functools.wraps(func)  # type: ignore
                def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = yield from self.parse(  # type: ignore
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args)
                        return func(*args, **kwargs)  # noqa: B901
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return func(*new_args, **kwargs)

            return wrapper

        return decorator
735334
def match_in_kwargs(self, match_args, kwargs):
        """"""
        for match, default in match_args:
            names = get_match_names(match)
            if names:
                tempvar = self.get_temp_var()
                self.add_def(
                    tempvar + " = "
                    + "".join(
                        kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else "
                        for name in names
                    )
                    + default,
                )
                with self.down_a_level():
                    self.match(match, tempvar)
            else:
                raise CoconutDeferredSyntaxError("keyword-only pattern-matching function arguments must have names", self.loc)
1133530
def add_argument(self, *args, **kwargs):
        

        # if no positional args are supplied or only one is supplied and
        # it doesn't look like an option string, parse a positional
        # argument
        chars = self.prefix_chars
        if not args or len(args) == 1 and args[0][0] not in chars:
            if args and 'dest' in kwargs:
                raise ValueError('dest supplied twice for positional argument')
            kwargs = self._get_positional_kwargs(*args, **kwargs)

        # otherwise, we're adding an optional argument
        else:
            kwargs = self._get_optional_kwargs(*args, **kwargs)

        # if no default was supplied, use the parser-level default
        if 'default' not in kwargs:
            dest = kwargs['dest']
            if dest in self._defaults:
                kwargs['default'] = self._defaults[dest]
            elif self.argument_default is not None:
                kwargs['default'] = self.argument_default

        # create the action object, and add it to the parser
        action_class = self._pop_action_class(kwargs)
        if not _callable(action_class):
            raise ValueError('unknown action "%s"' % action_class)
        action = action_class(**kwargs)

        # raise an error if the action type is not callable
        type_func = self._registry_get('type', action.type, action.type)
        if not _callable(type_func):
            raise ValueError('%r is not callable' % type_func)

        return self._add_action(action)
136906
def prepare_args(self, args, kwargs):
        
        args, kwargs = super().prepare_args(args, kwargs)
        form_kwargs = self.get_form_kwargs()
        self.form = self.Form(**form_kwargs)
        return args, kwargs
1281691
def AddArg(self, arg):
    
    self.args.append(arg)
    if len(self.args) > self.number_of_args:
      raise ParseError("Too many args for this expression.")

    elif len(self.args) == self.number_of_args:
      return True

    return False
547351
def kwargs(self, obj, kwargs):
        '''
        
        '''
        if hasattr(obj, "KWARGS"):
            for module_argument in obj.KWARGS:
                if has_key(kwargs, module_argument.name):
                    arg_value = kwargs[module_argument.name]
                else:
                    arg_value = copy(module_argument.default)

                setattr(obj, module_argument.name, arg_value)

            for (k, v) in iterator(kwargs):
                if not hasattr(obj, k):
                    setattr(obj, k, v)
        else:
            raise Exception("binwalk.core.module.Modules.process_kwargs: %s has no attribute 'KWARGS'" % str(obj))
715763
def r(self, **kwargs):
        
        # by using kwargs we ensure that usage of positional arguments, as if
        # this object were another kind of function, will fail-fast and raise
        # a TypeError
        kwargs.pop('default', None)
        if kwargs:
            raise TypeError(
                "Unexpected argument: {}".format(repr(next(iter(kwargs))))
            )
        return self._obj
559059
def get_boundargs(cls, *args, **kargs):
        
        boundargs = cls._signature.bind(*args, **kargs)
        # Include default arguments.
        for param in cls._signature.parameters.values():
            if (param.name not in boundargs.arguments and
                param.default is not param.empty):
                boundargs.arguments[param.name] = param.default
        return boundargs
883168
def return_arg_type(at_position):
    

    def decorator(to_wrap):
        @functools.wraps(to_wrap)
        def wrapper(*args, **kwargs):
            result = to_wrap(*args, **kwargs)
            ReturnType = type(args[at_position])
            return ReturnType(result)

        return wrapper

    return decorator
56411
def get_kwargs(**kwargs):
        
        d = dict()
        for k, v in kwargs.iteritems():
            if v is not NOTSET:
                d[k] = v
        return d