Exemple #1
0
    def test_getargspec_bound_methods(self):
        def f_expected_unbound(self, arg1, **kwargs):
            pass
        expected_unbound = inspect.getargspec(f_expected_unbound)

        def f_expected_bound(arg1, **kwargs):
            pass
        expected_bound = inspect.getargspec(f_expected_bound)

        class Foo:
            def method(self, arg1, **kwargs):
                pass

        bound_method = Foo().method

        @functools.wraps(bound_method)
        def wrapped_bound_method(*args, **kwargs):
            pass

        assert expected_unbound == inspect.getargspec(Foo.method)
        if PY3 and sys.version_info >= (3, 4, 4):
            # On py2, the inspect functions don't properly handle bound
            # methods (they include a spurious 'self' argument)
            assert expected_bound == inspect.getargspec(bound_method)
            # On py2, the inspect functions can't properly handle wrapped
            # functions (no __wrapped__ support)
            assert expected_bound == inspect.getargspec(wrapped_bound_method)
def test_getargspec_bound_methods():
    def f_expected_unbound(self, arg1, **kwargs):
        pass
    expected_unbound = inspect.getargspec(f_expected_unbound)

    def f_expected_bound(arg1, **kwargs):
        pass
    expected_bound = inspect.getargspec(f_expected_bound)

    class Foo:
        def method(self, arg1, **kwargs):
            pass

    bound_method = Foo().method

    @functools.wraps(bound_method)
    def wrapped_bound_method(*args, **kwargs):
        pass

    assert expected_unbound == inspect.getargspec(Foo.method)
    if PY3 and sys.version_info >= (3, 4, 4):
        # On py2, the inspect functions don't properly handle bound
        # methods (they include a spurious 'self' argument)
        assert expected_bound == inspect.getargspec(bound_method)
        # On py2, the inspect functions can't properly handle wrapped
        # functions (no __wrapped__ support)
        assert expected_bound == inspect.getargspec(wrapped_bound_method)
Exemple #3
0
def test_getargspec_partial2():
    def fun(a, b, c=1, d=2):
        pass

    p = functools.partial(fun, 10, c=11)

    if PY3:
        # Python 3's partial is rather cleverer than Python 2's, and we
        # have to jump through some hoops to define an equivalent function
        # in a way that won't confuse Python 2's parser:
        ns = {}
        exec(
            dedent("""
            def f_expected(b, *, c=11, d=2):
                    pass
        """), ns)
        f_expected = ns["f_expected"]
    else:

        def f_expected(b, d=2):
            pass

    expected = inspect.getargspec(f_expected)

    assert expected == inspect.getargspec(p)
Exemple #4
0
def test_getargspec_partial2():
    def fun(a, b, c=1, d=2):
        pass
    p = functools.partial(fun, 10, c=11)

    def f_expected(b, *, c=11, d=2):
        pass
    expected = inspect.getargspec(f_expected)

    assert expected == inspect.getargspec(p)
	def format_args(self):
		if isinstance(self.object, ThreadedSegment):
			args = ['interval']
			defaults = [getattr(self.object, 'interval', 1)]
			if self.object.update_first:
				args.append('update_first')
				defaults.append(True)
			methods = ['render', 'set_state']
			if isinstance(self.object, KwThreadedSegment):
				methods += ['key', 'render_one']

			for method in methods:
				if hasattr(self.object, method):
					# Note: on <python-2.6 it may return simple tuple, not 
					# ArgSpec instance.
					argspec = getargspec(getattr(self.object, method))
					for i, arg in zip(count(-1, -1), reversed(argspec.args)):
						if (arg == 'self' or
								(arg == 'segment_info' and
									getattr(self.object, 'powerline_requires_segment_info', None)) or
								(method == 'render_one' and -i == len(argspec.args)) or
								arg in args):
							continue
						if argspec.defaults and len(argspec.defaults) >= -i:
							default = argspec.defaults[i]
							defaults.append(default)
							args.append(arg)
						else:
							args.insert(0, arg)
			argspec = ArgSpec(args=args, varargs=None, keywords=None, defaults=tuple(defaults))
		else:
			if hasattr(self.object, 'powerline_origin'):
				obj = self.object.powerline_origin
			else:
				obj = self.object

			argspec = getargspec(obj)
			args = []
			defaults = []
			for i, arg in zip(count(-1, -1), reversed(argspec.args)):
				if (arg == 'segment_info' and getattr(self.object, 'powerline_requires_segment_info', None)):
					continue
				if argspec.defaults and len(argspec.defaults) >= -i:
					default = argspec.defaults[i]
					defaults.append(default)
					args.append(arg)
				else:
					args.insert(0, arg)
			argspec = ArgSpec(args=args, varargs=argspec.varargs, keywords=argspec.keywords, defaults=tuple(defaults))

		return formatargspec(*argspec, formatvalue=formatvalue).replace('\\', '\\\\')
def process_signature(app, what: str, name: str, obj, options, signature, return_annotation):
    if not callable(obj):
        return

    if what in ('class', 'exception'):
        obj = getattr(obj, '__init__', getattr(obj, '__new__', None))

    if not getattr(obj, '__annotations__', None):
        return

    obj = unwrap(obj)
    try:
        argspec = getargspec(obj)
    except (TypeError, ValueError):
        return

    if argspec.args:
        if what in ('class', 'exception'):
            del argspec.args[0]
        elif what == 'method':
            outer = inspect.getmodule(obj)
            for clsname in obj.__qualname__.split('.')[:-1]:
                outer = getattr(outer, clsname)
            method_object = outer.__dict__[obj.__name__]
            if not isinstance(method_object, (classmethod, staticmethod)):
                del argspec.args[0]

    try:
        result = formatargspec(obj, *argspec[:-1]), None
    except NameError:
        # This happens when the type annotation is conditionally imported with TYPE_CHECKING
        return

    return result
def process_signature(app, what: str, name: str, obj, options, signature,
                      return_annotation):
    if not callable(obj):
        return

    if what in ('class', 'exception'):
        obj = getattr(obj, '__init__', getattr(obj, '__new__', None))

    if not getattr(obj, '__annotations__', None):
        return

    obj = unwrap(obj)
    try:
        argspec = getargspec(obj)
    except (TypeError, ValueError):
        return

    if argspec.args:
        if what in ('class', 'exception'):
            del argspec.args[0]
        elif what == 'method':
            module = inspect.getmodule(obj)
            clsname = obj.__qualname__.rsplit('.', 1)[0]
            cls = getattr(module, clsname)
            method_object = cls.__dict__[obj.__name__]
            if not isinstance(method_object, (classmethod, staticmethod)):
                del argspec.args[0]

    return formatargspec(obj, *argspec[:-1]), None
Exemple #8
0
def _format_method_args(obj):
    if inspect.isbuiltin(obj) or \
           inspect.ismethoddescriptor(obj):
        # can never get arguments of a C function or method
        return None
    argspec = getargspec(obj)
    if argspec[0] and argspec[0][0] in ('cls', 'self'):
        del argspec[0][0]
    return inspect.formatargspec(*argspec)
Exemple #9
0
def _format_method_args(obj):
    if inspect.isbuiltin(obj) or \
            inspect.ismethoddescriptor(obj):
        # can never get arguments of a C function or method
        return None
    argspec = getargspec(obj)
    if argspec[0] and argspec[0][0] in ('cls', 'self'):
        del argspec[0][0]
    return inspect.formatargspec(*argspec)
Exemple #10
0
 def format_args(self):
     function = self.object.body
     # TODO: consider extending (or adding a sibling to) Task.argspec so it
     # preserves more of the full argspec tuple.
     # TODO: whether to preserve the initial context argument is an open
     # question. For now, it will appear, but only pending invoke#170 -
     # after which point "call tasks as raw functions" may be less common.
     # TODO: also, it may become moot-ish if we turn this all into emission
     # of custom domain objects and/or make the CLI arguments the focus
     return autodoc.formatargspec(function, *getargspec(function))
Exemple #11
0
 def format_args(self):
     function = self.object.body
     # TODO: consider extending (or adding a sibling to) Task.argspec so it
     # preserves more of the full argspec tuple.
     # TODO: whether to preserve the initial context argument is an open
     # question. For now, it will appear, but only pending invoke#170 -
     # after which point "call tasks as raw functions" may be less common.
     # TODO: also, it may become moot-ish if we turn this all into emission
     # of custom domain objects and/or make the CLI arguments the focus
     return autodoc.formatargspec(function, *getargspec(function))
Exemple #12
0
def wrapped_getargspec(fun, *args, **kwargs):
    while 1:
        try:
            wrapped = fun.__wrapped__
            if wrapped is fun:
                break
            fun = wrapped
        except AttributeError:
            break
    return inspect.getargspec(fun, *args, **kwargs)
def wrapped_getargspec(fun, *args, **kwargs):
    while 1:
        try:
            wrapped = fun.__wrapped__
            if wrapped is fun:
                break
            fun = wrapped
        except AttributeError:
            break
    return inspect.getargspec(fun, *args, **kwargs)
Exemple #14
0
def test_getargspec():
    def func(a, b, c=1, d=2, *e, **f):
        pass

    spec = inspect.getargspec(func)
    assert spec.args == ['a', 'b', 'c', 'd']
    assert spec.varargs == 'e'
    assert spec.varkw == 'f'
    assert spec.defaults == (1, 2)
    assert spec.kwonlyargs == []
    assert spec.kwonlydefaults is None
    assert spec.annotations == {}
def test_getargspec():
    def func(a, b, c=1, d=2, *e, **f):
        pass

    spec = inspect.getargspec(func)
    assert spec.args == ['a', 'b', 'c', 'd']
    assert spec.varargs == 'e'
    assert spec.varkw == 'f'
    assert spec.defaults == (1, 2)
    assert spec.kwonlyargs == []
    assert spec.kwonlydefaults is None
    assert spec.annotations == {}
Exemple #16
0
def _format_function_args(obj):
    if inspect.isbuiltin(obj) or \
            inspect.ismethoddescriptor(obj):
        # cannot introspect arguments of a C function or method
        return None
    try:
        argspec = getargspec(obj)
    except TypeError:
        # if a class should be documented as function (yay duck
        # typing) we try to use the constructor signature as function
        # signature without the first argument.
        try:
            argspec = getargspec(obj.__new__)
        except TypeError:
            argspec = getargspec(obj.__init__)
            if argspec[0]:
                del argspec[0][0]
    args = inspect.formatargspec(*argspec)
    # escape backslashes for reST
    args = args.replace('\\', '\\\\')
    return args
Exemple #17
0
def _format_function_args(obj):
    if inspect.isbuiltin(obj) or \
           inspect.ismethoddescriptor(obj):
        # cannot introspect arguments of a C function or method
        return None
    try:
        argspec = getargspec(obj)
    except TypeError:
        # if a class should be documented as function (yay duck
        # typing) we try to use the constructor signature as function
        # signature without the first argument.
        try:
            argspec = getargspec(obj.__new__)
        except TypeError:
            argspec = getargspec(obj.__init__)
            if argspec[0]:
                del argspec[0][0]
    args = inspect.formatargspec(*argspec)
    # escape backslashes for reST
    args = args.replace('\\', '\\\\')
    return args
Exemple #18
0
    def test_getargspec_partial(self):
        def fun(a, b, c=1, d=2):
            pass
        p = functools.partial(fun, 10, c=11)

        if PY3:
            # Python 3's partial is rather cleverer than Python 2's, and we
            # have to jump through some hoops to define an equivalent function
            # in a way that won't confuse Python 2's parser:
            ns = {}
            exec(dedent("""
                def f_expected(b, *, c=11, d=2):
                        pass
            """), ns)
            f_expected = ns["f_expected"]
        else:
            def f_expected(b, d=2):
                pass
        expected = inspect.getargspec(f_expected)

        assert expected == inspect.getargspec(p)
Exemple #19
0
def test_getargspec_bound_methods():
    def f_expected_unbound(self, arg1, **kwargs):
        pass
    expected_unbound = inspect.getargspec(f_expected_unbound)

    def f_expected_bound(arg1, **kwargs):
        pass
    expected_bound = inspect.getargspec(f_expected_bound)

    class Foo:
        def method(self, arg1, **kwargs):
            pass

    bound_method = Foo().method

    @functools.wraps(bound_method)
    def wrapped_bound_method(*args, **kwargs):
        pass

    assert expected_unbound == inspect.getargspec(Foo.method)
    assert expected_bound == inspect.getargspec(bound_method)
    assert expected_bound == inspect.getargspec(wrapped_bound_method)
Exemple #20
0
def test_getargspec_partial():
    def func1(a, b, c=1, d=2, *e, **f):
        pass

    partial = functools.partial(func1, 10, c=11)
    spec = inspect.getargspec(partial)
    assert spec.args == ['b']
    assert spec.varargs is None
    assert spec.varkw == 'f'
    assert spec.defaults is None
    assert spec.kwonlyargs == ['c', 'd']
    assert spec.kwonlydefaults == {'c': 11, 'd': 2}
    assert spec.annotations == {}
def test_getargspec_partial():
    def func1(a, b, c=1, d=2, *e, **f):
        pass

    partial = functools.partial(func1, 10, c=11)
    spec = inspect.getargspec(partial)
    assert spec.args == ['b']
    assert spec.varargs is None
    assert spec.varkw == 'f'
    assert spec.defaults is None
    assert spec.kwonlyargs == ['c', 'd']
    assert spec.kwonlydefaults == {'c': 11, 'd': 2}
    assert spec.annotations == {}
def process_signature(app, what: str, name: str, obj, options, signature, return_annotation):
    if callable(obj):
        if what in ('class', 'exception'):
            obj = getattr(obj, '__init__')

        try:
            argspec = getargspec(obj)
        except TypeError:
            return

        if what in ('method', 'class', 'exception') and argspec.args:
            del argspec.args[0]

        return formatargspec(obj, *argspec[:-1]), None
Exemple #23
0
def process_signature(app, what: str, name: str, obj, options, signature, return_annotation):
    if callable(obj) and getattr(obj, '__annotations__', None):
        if what in ('class', 'exception'):
            obj = getattr(obj, '__init__')

        obj = unwrap(obj)
        try:
            argspec = getargspec(obj)
        except (TypeError, ValueError):
            return

        if what in ('method', 'class', 'exception') and argspec.args:
            del argspec.args[0]

        return formatargspec(obj, *argspec[:-1]), None
Exemple #24
0
    def __enter__(self):
        import inspect
        import subprocess
        if os.name == 'nt':
            origInit = subprocess.Popen.__init__.__func__
            self.origInit = origInit

            argspec = inspect.getargspec(self.origInit)
            creationflags_index = argspec.args.index('creationflags')
            CREATE_NO_WINDOW_FLAG = 0x08000000

            def __init__(self, *args, **kwargs):
                if (len(args) <= creationflags_index
                        and 'creationflags' not in kwargs):
                    kwargs['creationflags'] = CREATE_NO_WINDOW_FLAG
                    return origInit(self, *args, **kwargs)

            subprocess.Popen.__init__ = __init__
        else:
            self.origInit = None
def process_signature(app, what: str, name: str, obj, options, signature,
                      return_annotation):
    if not callable(obj):
        return

    if what in ('class', 'exception'):
        obj = getattr(obj, '__init__', getattr(obj, '__new__', None))

    if not getattr(obj, '__annotations__', None):
        return

    obj = unwrap(obj)
    try:
        argspec = getargspec(obj)
    except (TypeError, ValueError):
        return

    if argspec.args:
        if what in ('class', 'exception'):
            del argspec.args[0]
        elif what == 'method':
            outer = inspect.getmodule(obj)
            for clsname in obj.__qualname__.split('.')[:-1]:
                outer = getattr(outer, clsname)

            method_name = obj.__name__
            if method_name.startswith("__") and not method_name.endswith("__"):
                # If the method starts with double underscore (dunder)
                # Python applies mangling so we need to prepend the class name.
                # This doesn't happen if it always ends with double underscore.
                class_name = obj.__qualname__.split('.')[-2]
                method_name = "_{c}{m}".format(c=class_name, m=method_name)

            method_object = outer.__dict__[method_name]
            if not isinstance(method_object, (classmethod, staticmethod)):
                del argspec.args[0]

    return formatargspec(obj, *argspec[:-1]), None
def format_args(func):
    arg_spec = getargspec(func)
    if arg_spec[0][0] == 'self':  # Should always be true
        del(arg_spec[0][0])
    return formatargspec(*arg_spec)
Exemple #27
0
def format_args(func):
    arg_spec = getargspec(func)
    if arg_spec[0][0] == 'self':  # Should always be true
        del (arg_spec[0][0])
    return formatargspec(*arg_spec)
Exemple #28
0
 def verify_arg_spec(f, expected):
     eq_(formatargspec(f, *getargspec(f)), expected)
def test_getargspec_builtin_type():
    with pytest.raises(TypeError):
        inspect.getargspec(int)
Exemple #30
0
 def verify_arg_spec(f, expected):
     eq_(formatargspec(f, *getargspec(f)), expected)
Exemple #31
0
 def verify_arg_spec(f, expected):
     assert formatargspec(f, *getargspec(f)) == expected
Exemple #32
0
def test_getargspec_builtin_type():
    with pytest.raises(TypeError):
        inspect.getargspec(int)
Exemple #33
0
 def verify_arg_spec(f, expected):
     assert formatargspec(f, *getargspec(f)) == expected