首页 > 解决方案 > 在正文中传播函数参数

问题描述

可能是一个愚蠢的问题,但出于好奇而问

在python中,我可以传播*args**kwargs在函数的签名中

def my_func(foo, bar):
   print(f"foo={foo}, bar={bar}")

my_func(1, 2)          # 1 2
my_func(1, bar=2)      # 1 2
my_func(foo=1, bar=2)  # 1 2

是否可以将它传播到这样的函数体中?

def my_func(*args, **kwargs):
   foo, bar = *args, **kwargs       <=== Something like this

   print(f"foo={foo}, bar={bar}")

my_func(1, 2)          # 1 2
my_func(1, bar=2)      # 1 2
my_func(foo=1, bar=2)  # 1 2

标签: python

解决方案


args是一个元组,不是foo.

kwargs是 a dict,而不是 的值bar

def my_func(*args, **kwargs):
   foo = args[0]  # Assumes there is at least one positional argument
   bar = kwargs['bar']  # Assumes there is a keyword argument named bar

   print(f"foo={foo}, bar={bar}")

my_func(1, bar=2)                   # 1 2

如果您放弃使用签名,则必须明确说明位置参数到名称的映射。例如,

def my_func(*args, **kwargs):
    if len(args) == 0 and `foo` not in kwargs:
        raise TypeError("Missing argument for 'foo'")
    else:
        try:
            foo = args[0]
        except IndexError:
            foo = kwargs['foo']

    if len(args) == 1 and `bar` not in kwargs:
        raise TypeError("Missing argument for 'bar'")
    else:
        try:
            bar = args[1]
        except IndexError:
            bar = kwargs['bar']

    ....

在这里,我假设位置参数应该优先于关键字参数。您还可以使关键字参数优先

def my_func(*args, **kwargs):
    if len(args) == 0 and `foo` not in kwargs:
        raise TypeError("Missing argument for 'foo'")
    else:
        try:
            foo = kwargs['foo'
        except IndexError:
            foo = args[0]

    if len(args) == 1 and `bar` not in kwargs:
        raise TypeError("Missing argument for 'bar'")
    else:
        try:
            bar = kwargs['bar']
        except IndexError:
            bar = args[1]

    ....

或继续将尝试同时使用两者视为错误:

def my_func(*args, **kwargs):
    if len(args) == 0 and `foo` not in kwargs:
        raise TypeError("Missing argument for 'foo'")
    elif len(args) > 0 and `foo` in kwargs:
        raise TypeError("Multiple attempts to assign foo")
    else:
        try:
            foo = args[0]
        except IndexError:
            foo = kwargs['foo']

    if len(args) == 1 and `bar` not in kwargs:
        raise TypeError("Missing argument for 'bar'")
     elif len(args) > 1 and `bar` in kwargs:
        raise TypeError("Multiple attempts to assign bar")      
    else:
        try:
            bar = args[1]
        except IndexError:
            bar = kwargs['bar']

    ....

推荐阅读