计算有多少参数作为位置传递

Count how many arguments passed as positional

如果我有一个函数

def foo(x, y):
    pass

我如何从函数内部判断 y 是按位置传递还是使用关键字传递?

我想要类似的东西

def foo(x, y):
    if passed_positionally(y):
        print('y was passed positionally!')
    else:
        print('y was passed with its keyword')

所以我得到

>>> foo(3, 4)
y was passed positionally
>>> foo(3, y=4)
y was passed with its keyword

我意识到我最初并没有指定这一点,但是否可以在保留类型注释的同时这样做?到目前为止的最佳答案建议使用装饰器 - 但是,它不会保留 return 类型

您可以欺骗用户并向函数添加另一个参数,如下所示:

def foo(x,y1=None,y=None):
  if y1 is not None:
    print('y was passed positionally!')
  else:
    print('y was passed with its keyword')

我不建议这样做,但确实有效

你可以像这样创建一个装饰器:

def checkargs(func):
    def inner(*args, **kwargs):
        if 'y' in kwargs:
            print('y passed with its keyword!')
        else:
            print('y passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y):
...:     return x + y

>>> foo(2, 3)
y passed positionally.
5

>>> foo(2, y=3)
y passed with its keyword!
5

当然,您可以通过允许装饰器接受参数来改进这一点。因此,您可以传递要检查的参数。应该是这样的:

def checkargs(param_to_check):
    def inner(func):
        def wrapper(*args, **kwargs):
            if param_to_check in kwargs:
                print('y passed with its keyword!')
            else:
                print('y passed positionally.')
            result = func(*args, **kwargs)
            return result
        return wrapper
    return inner

>>>  @checkargs(param_to_check='y')
...: def foo(x, y):
...:     return x + y

>>> foo(2, y=3)
y passed with its keyword!
5

我想加上 functools.wraps would preserve the annotations, following version also allows to perform the check over all arguments (using inspect):

from functools import wraps
import inspect

def checkargs(func):
    @wraps(func)
    def inner(*args, **kwargs):
        for param in inspect.signature(func).parameters:
            if param in kwargs:
                print(param, 'passed with its keyword!')
            else:
                print(param, 'passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y, z) -> int:
...:     return x + y

>>> foo(2, 3, z=4)
x passed positionally.
y passed positionally.
z passed with its keyword!
9

>>> inspect.getfullargspec(foo)
FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None, 
kwonlyargs=[], kwonlydefaults=None, annotations={'return': <class 'int'>})
                                             _____________HERE____________

最后,如果你打算做这样的事情:

def foo(x, y):
    if passed_positionally(y):
        raise Exception("You need to pass 'y' as a keyword argument")
    else:
        process(x, y)

你可以这样做:

def foo(x, *, y):
    pass

>>> foo(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 1 positional argument but 2 were given

>>> foo(1, y=2) # works

或者只允许按位置传递:

def foo(x, y, /):
    pass

>>> foo(x=1, y=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'x, y'

>>> foo(1, 2) # works

有关更多信息,请参阅 PEP 570 and PEP 3102

这通常是不可能的。从某种意义上说:语言并不是为了让你区分这两种方式而设计的。

您可以将函数设计为采用不同的参数 - 位置参数和命名参数,并检查传递了哪一个参数,例如:

def foo(x, y=None, /, **kwargs):
 
    if y is None: 
        y = kwargs.pop(y)
        received_as_positional = False
    else:
        received_as_positional = True

问题是,尽管通过使用上述仅位置参数,您可以通过两种方式获得 y, 对于检查的用户(或 IDE),它不会显示一次 函数签名。

我觉得你只是为了了解而想了解这个 - 如果 你真的打算用这个来设计 API,我建议你重新考虑一下 你的 API - 行为应该没有区别,除非两者 从用户的角度来看是明确不同的参数。

也就是说,要走的路是检查调用者框架,然后检查 函数调用处的字节码:


In [24]: import sys, dis

In [25]: def foo(x, y=None):
    ...:     f = sys._getframe().f_back
    ...:     print(dis.dis(f.f_code))
    ...: 

In [26]: foo(1, 2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 CALL_FUNCTION            2
              8 PRINT_EXPR
             10 LOAD_CONST               2 (None)
             12 RETURN_VALUE
None

In [27]: foo(1, y=2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 (('y',))
              8 CALL_FUNCTION_KW         2
             10 PRINT_EXPR
             12 LOAD_CONST               3 (None)
             14 RETURN_VALUE

所以,正如你所看到的,当 y 作为命名参数调用时,调用的操作码是 CALL_FUNCTION_KW ,并且参数的名称在它之前立即加载到堆栈中.

foo中,你可以将调用堆栈从traceback传递给positionally,然后positionally将解析这些行,找到调用foo本身的行,然后解析带有 ast 的行以定位位置参数规范(如果有):

import traceback, ast, re
def get_fun(name, ast_obj):
    if isinstance(ast_obj, ast.Call) and ast_obj.func.id == name:
        yield from [i.arg for i in getattr(ast_obj, 'keywords', [])]
    for a, b in getattr(ast_obj, '__dict__', {}).items():
        yield from (get_fun(name, b) if not isinstance(b, list) else \
                        [i for k in b for i in get_fun(name, k)])

def passed_positionally(stack):
    *_, [_, co], [trace, _] = [re.split('\n\s+', i.strip()) for i in stack] 
    f_name = re.findall('(?:line \d+, in )(\w+)', trace)[0]
    return list(get_fun(f_name, ast.parse(co)))

def foo(x, y):
    if 'y' in passed_positionally(traceback.format_stack()):
        print('y was passed with its keyword')
    else:
        print('y was passed positionally')

foo(1, y=2)

输出:

y was passed with its keyword

备注:

  1. 此解决方案不需要 foo 的任何包装。只需要捕获回溯。
  2. 要在回溯中以字符串形式获取完整的 foo 调用,此解决方案必须在文件中 运行,而不是 shell.

改编自@Cyttorak 的回答,这是一种维护类型的方法:

from typing import TypeVar, Callable, Any, TYPE_CHECKING

T = TypeVar("T", bound=Callable[..., Any])

from functools import wraps
import inspect

def checkargs() -> Callable[[T], T]:
    def decorate(func):
        @wraps(func)
        def inner(*args, **kwargs):
            for param in inspect.signature(func).parameters:
                if param in kwargs:
                    print(param, 'passed with its keyword!')
                else:
                    print(param, 'passed positionally.')
            result = func(*args, **kwargs)
            return result
        return inner
    return decorate

@checkargs()
def foo(x, y) -> int:
    return x+y

if TYPE_CHECKING:
    reveal_type(foo(2, 3))
foo(2, 3)
foo(2, y=3)

输出为:

$ mypy t.py 
t.py:27: note: Revealed type is 'builtins.int'
$ python t.py 
x passed positionally.
y passed positionally.
x passed positionally.
y passed with its keyword!