Exemplo n.º 1
0
    def get_args(self):
        """Check if an unclosed parenthesis exists, then attempt to get the
        argspec() for it. On success, update self.funcprops,self.arg_pos and
        return True, otherwise set self.funcprops to None and return False"""

        self.current_func = None

        if not self.config.arg_spec:
            return False

        func, arg_number = self._funcname_and_argnum(self.current_line)
        if not func:
            return False

        try:
            if inspection.is_eval_safe_name(func):
                f = self.get_object(func)
            else:
                try:
                    fake_cursor = self.current_line.index(func) + len(func)
                    f = simpleeval.evaluate_current_attribute(
                            fake_cursor, self.current_line, self.interp.locals)
                except simpleeval.EvaluationError:
                    return False
        except Exception:
            # another case of needing to catch every kind of error
            # since user code is run in the case of descriptors
            # XXX: Make sure you raise here if you're debugging the completion
            # stuff !
            return False

        if inspect.isclass(f):
            class_f = None

            if (hasattr(f, '__init__') and
                    f.__init__ is not object.__init__):
                class_f = f.__init__
            if ((not class_f or
                 not inspection.getfuncprops(func, class_f)) and
                    hasattr(f, '__new__') and
                    f.__new__ is not object.__new__ and
                    # py3
                    f.__new__.__class__ is not object.__new__.__class__):

                class_f = f.__new__

            if class_f:
                f = class_f

        self.current_func = f
        self.funcprops = inspection.getfuncprops(func, f)
        if self.funcprops:
            self.arg_pos = arg_number
            return True
        self.arg_pos = None
        return False
Exemplo n.º 2
0
    def get_args(self):
        """Check if an unclosed parenthesis exists, then attempt to get the
        argspec() for it. On success, update self.funcprops,self.arg_pos and
        return True, otherwise set self.funcprops to None and return False"""

        self.current_func = None

        if not self.config.arg_spec:
            return False

        func, arg_number = self._funcname_and_argnum(self.current_line)
        if not func:
            return False

        try:
            if inspection.is_eval_safe_name(func):
                f = self.get_object(func)
            else:
                try:
                    fake_cursor = self.current_line.index(func) + len(func)
                    f = simpleeval.evaluate_current_attribute(
                            fake_cursor, self.current_line, self.interp.locals)
                except simpleeval.EvaluationError:
                    return False
        except Exception:
            # another case of needing to catch every kind of error
            # since user code is run in the case of descriptors
            # XXX: Make sure you raise here if you're debugging the completion
            # stuff !
            return False

        if inspect.isclass(f):
            class_f = None

            if (hasattr(f, '__init__') and
                    f.__init__ is not object.__init__):
                class_f = f.__init__
            if ((not class_f or
                 not inspection.getfuncprops(func, class_f)) and
                    hasattr(f, '__new__') and
                    f.__new__ is not object.__new__ and
                    # py3
                    f.__new__.__class__ is not object.__new__.__class__):

                class_f = f.__new__

            if class_f:
                f = class_f

        self.current_func = f
        self.funcprops = inspection.getfuncprops(func, f)
        if self.funcprops:
            self.arg_pos = arg_number
            return True
        self.arg_pos = None
        return False
Exemplo n.º 3
0
    def test_parsekeywordpairs_multiple_keywords(self):
        def spam(eggs=23, foobar="yay"):
            pass

        defaults = inspection.getfuncprops("spam", spam).argspec.defaults
        self.assertEqual(repr(defaults[0]), "23")
        self.assertEqual(repr(defaults[1]), "'yay'")
Exemplo n.º 4
0
    def test_getfuncprops_numpy_array(self):
        props = inspection.getfuncprops("array", numpy.array)

        self.assertEqual(props.func, "array")
        # This check might need an update in the future, but at least numpy >= 1.18 has
        # np.array(object, dtype=None, *, ...).
        self.assertEqual(props.argspec.args, ["object", "dtype"])
Exemplo n.º 5
0
    def test_getfuncprops_print(self):
        props = inspection.getfuncprops("print", print)

        self.assertEqual(props.func, "print")
        self.assertIn("end", props.argspec.kwonly)
        self.assertIn("file", props.argspec.kwonly)
        self.assertIn("flush", props.argspec.kwonly)
        self.assertIn("sep", props.argspec.kwonly)
        self.assertEqual(props.argspec.kwonly_defaults["file"], "sys.stdout")
        self.assertEqual(props.argspec.kwonly_defaults["flush"], "False")
Exemplo n.º 6
0
 def test_argspec(self):
     def foo(x, y, z=10):
         "docstring!"
         pass
     argspec = inspection.getfuncprops('foo', foo)
     array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
     screen = [bold(cyan('foo')) + cyan(':') + cyan(' ') + cyan('(') +
               cyan('x') + yellow(',') + yellow(' ') + bold(cyan('y')) +
               yellow(',') + yellow(' ') + cyan('z') + yellow('=') +
               bold(cyan('10')) + yellow(')')]
     self.assertFSArraysEqual(fsarray(array), fsarray(screen))
Exemplo n.º 7
0
    def test_parsekeywordpairs(self):
        # See issue #109
        def fails(spam=["-a", "-b"]):
            pass

        default_arg_repr = "['-a', '-b']"
        self.assertEqual(str(["-a", "-b"]), default_arg_repr, "This test is broken (repr does not match), fix me.")

        argspec = inspection.getfuncprops("fails", fails)
        defaults = argspec.argspec.defaults
        self.assertEqual(str(defaults[0]), default_arg_repr)
 def test_argspec(self):
     def foo(x, y, z=10):
         "docstring!"
         pass
     argspec = inspection.getfuncprops('foo', foo)
     array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
     screen = [bold(cyan('foo')) + cyan(':') + cyan(' ') + cyan('(') +
               cyan('x') + yellow(',') + yellow(' ') + bold(cyan('y')) +
               yellow(',') + yellow(' ') + cyan('z') + yellow('=') +
               bold(cyan('10')) + yellow(')')]
     self.assertFSArraysEqual(fsarray(array), fsarray(screen))
Exemplo n.º 9
0
    def test_parsekeywordpairs(self):
        # See issue #109
        def fails(spam=['-a', '-b']):
            pass

        default_arg_repr = "['-a', '-b']"
        self.assertEqual(str(['-a', '-b']), default_arg_repr,
                         'This test is broken (repr does not match), fix me.')

        argspec = inspection.getfuncprops('fails', fails)
        defaults = argspec.argspec.defaults
        self.assertEqual(str(defaults[0]), default_arg_repr)
Exemplo n.º 10
0
    def test_argspec(self):
        def foo(x, y, z=10):
            "docstring!"
            pass

        argspec = inspection.getfuncprops("foo", foo)
        array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
        screen = [
            bold(cyan("foo")) + cyan(":") + cyan(" ") + cyan("(") + cyan("x") +
            yellow(",") + yellow(" ") + bold(cyan("y")) + yellow(",") +
            yellow(" ") + cyan("z") + yellow("=") + bold(cyan("10")) +
            yellow(")")
        ]
        assertFSArraysEqual(fsarray(array), fsarray(screen))
Exemplo n.º 11
0
    def get_args(self):
        """Check if an unclosed parenthesis exists, then attempt to get the
        argspec() for it. On success, update self.funcprops,self.arg_pos and
        return True, otherwise set self.funcprops to None and return False"""

        self.current_func = None

        if not self.config.arg_spec:
            return False

        # Get the name of the current function and where we are in
        # the arguments
        stack = [['', 0, '']]
        try:
            for (token, value) in PythonLexer().get_tokens(
                    self.current_line):
                if token is Token.Punctuation:
                    if value in '([{':
                        stack.append(['', 0, value])
                    elif value in ')]}':
                        stack.pop()
                    elif value == ',':
                        try:
                            stack[-1][1] += 1
                        except TypeError:
                            stack[-1][1] = ''
                        stack[-1][0] = ''
                    elif value == ':' and stack[-1][2] == 'lambda':
                        stack.pop()
                    else:
                        stack[-1][0] = ''
                elif (token is Token.Name or token in Token.Name.subtypes or
                      token is Token.Operator and value == '.'):
                    stack[-1][0] += value
                elif token is Token.Operator and value == '=':
                    stack[-1][1] = stack[-1][0]
                    stack[-1][0] = ''
                elif token is Token.Keyword and value == 'lambda':
                    stack.append(['', 0, value])
                else:
                    stack[-1][0] = ''
            while stack[-1][2] in '[{':
                stack.pop()
            _, arg_number, _ = stack.pop()
            func, _, _ = stack.pop()
        except IndexError:
            return False
        if not func:
            return False

        try:
            if inspection.is_eval_safe_name(func):
                f = self.get_object(func)
            else:
                try:
                    fake_cursor = self.current_line.index(func) + len(func)
                    f = simpleeval.evaluate_current_attribute(
                            fake_cursor, self.current_line, self.interp.locals)
                except simpleeval.EvaluationError:
                    return False
        except Exception:
            # another case of needing to catch every kind of error
            # since user code is run in the case of descriptors
            # XXX: Make sure you raise here if you're debugging the completion
            # stuff !
            return False

        if inspect.isclass(f):
            class_f = None

            if (hasattr(f, '__init__') and
                    f.__init__ is not object.__init__):
                class_f = f.__init__
            if ((not class_f or
                 not inspection.getfuncprops(func, class_f)) and
                    hasattr(f, '__new__') and
                    f.__new__ is not object.__new__ and
                    # py3
                    f.__new__.__class__ is not object.__new__.__class__):

                class_f = f.__new__

            if class_f:
                f = class_f

        self.current_func = f
        self.funcprops = inspection.getfuncprops(func, f)
        if self.funcprops:
            self.arg_pos = arg_number
            return True
        self.arg_pos = None
        return False
Exemplo n.º 12
0
    def test_pasekeywordpairs_string(self):
        def spam(eggs="foo, bar"):
            pass

        defaults = inspection.getfuncprops("spam", spam).argspec.defaults
        self.assertEqual(repr(defaults[0]), "'foo, bar'")
Exemplo n.º 13
0
    def get_args(self):
        """Check if an unclosed parenthesis exists, then attempt to get the
        argspec() for it. On success, update self.funcprops,self.arg_pos and
        return True, otherwise set self.funcprops to None and return False"""

        self.current_func = None

        if not self.config.arg_spec:
            return False

        # Get the name of the current function and where we are in
        # the arguments
        stack = [['', 0, '']]
        try:
            for (token, value) in PythonLexer().get_tokens(self.current_line):
                if token is Token.Punctuation:
                    if value in '([{':
                        stack.append(['', 0, value])
                    elif value in ')]}':
                        stack.pop()
                    elif value == ',':
                        try:
                            stack[-1][1] += 1
                        except TypeError:
                            stack[-1][1] = ''
                        stack[-1][0] = ''
                    elif value == ':' and stack[-1][2] == 'lambda':
                        stack.pop()
                    else:
                        stack[-1][0] = ''
                elif (token is Token.Name or token in Token.Name.subtypes
                      or token is Token.Operator and value == '.'):
                    stack[-1][0] += value
                elif token is Token.Operator and value == '=':
                    stack[-1][1] = stack[-1][0]
                    stack[-1][0] = ''
                elif token is Token.Keyword and value == 'lambda':
                    stack.append(['', 0, value])
                else:
                    stack[-1][0] = ''
            while stack[-1][2] in '[{':
                stack.pop()
            _, arg_number, _ = stack.pop()
            func, _, _ = stack.pop()
        except IndexError:
            return False
        if not func:
            return False

        try:
            f = self.get_object(func)
        except Exception:
            # another case of needing to catch every kind of error
            # since user code is run in the case of descriptors
            # XXX: Make sure you raise here if you're debugging the completion
            # stuff !
            return False

        if inspect.isclass(f):
            class_f = None

            if (hasattr(f, '__init__') and f.__init__ is not object.__init__):
                class_f = f.__init__
            if ((not class_f or not inspection.getfuncprops(func, class_f))
                    and hasattr(f, '__new__')
                    and f.__new__ is not object.__new__ and f.__new__.__class__
                    is not object.__new__.__class__):  # py3
                class_f = f.__new__

            if class_f:
                f = class_f

        self.current_func = f
        self.funcprops = inspection.getfuncprops(func, f)
        if self.funcprops:
            self.arg_pos = arg_number
            return True
        self.arg_pos = None
        return False