Esempio n. 1
0
    def check_init_obj(self, params=None):
        """ check if the function used for init can be used in this API
        -> must allow **kwargs and *args.
        All arguments must have a value: either a default one or specified in
        the input dict *params*
        """
        args, varargs, varkw, defaults = getargspec(self._init_obj)
        if varkw is not None:  # we don't want **kwargs arguments
            raise Exception(
                "Keywords dict argument (eg **kwargs) " "not supported (init function:%s)." % str(self._init_obj)
            )
        if varargs is not None:  # we don't want *args arguments
            raise Exception(
                "Positional list argument (eg *args) " " not supported (init function:%s)" % str(self._init_obj)
            )
        if args[0] == "self":
            args = args[1:]
        if params is not None:
            if set(params.keys()) != set(args):
                raise Exception(
                    "Some arguments do not  " "have a value: %s" % (str(set(args).difference(params.keys())))
                )

        elif len(args) - 1 != len(defaults):
            pos_args = args[: len(args) - len(defaults)]
            print "pos_args:", pos_args
            raise Exception(
                'In init function "%s.%s", some arguments are '
                "not keywords arguments: %s" % (str(self.__class__), str(self._init_obj.__name__), ",".join(pos_args))
            )
Esempio n. 2
0
    def set_init(self, init_obj, **init_params):
        """ Override init function with *init_obj* and use *init_params*
        as new init parameters. *init_obj* must return an instance of the
        same class as the current object. Useful when the object is not
        instanciated via its __init__ function but eg a static method.
        """
        self._init_obj = init_obj
        args, varargs, varkw, defaults = getargspec(self._init_obj)

        self.check_init_obj(init_params)
        self._init_parameters = dict((k, copy(v)) for k, v in init_params.iteritems())

        for ip in self._init_parameters:
            if ip not in args:
                raise Exception(
                    'Init parameter "%s" is not an argument of '
                    'init function "%s". Args are: %s' % (ip, str(self._init_obj), ",".join(args))
                )