代码之家  ›  专栏  ›  技术社区  ›  Andrey Fedorov

有没有一种方法可以在不调用typeerror的情况下使用错误数量的参数来调用python函数?

  •  1
  • Andrey Fedorov  · 技术社区  · 15 年前

    当使用错误数量的参数或其定义中没有的关键字参数调用函数时,您将得到一个类型错误。我希望使用一段代码进行回调,并根据回调支持的内容使用变量参数来调用它。一种方法是,回拨 cb 使用 cb.__code__.cb_argcount cb.__code__.co_varnames 但是我想把它抽象成 apply 但这只适用于“合适”的论点。

    例如:

     def foo(x,y,z):
       pass
    
     cleanvoke(foo, 1)         # should call foo(1, None, None)
     cleanvoke(foo, y=2)       # should call foo(None, 2, None)
     cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3)
                               # etc.
    

    在python中是否已经有类似的东西,或者是我应该从头开始写的东西?

    2 回复  |  直到 14 年前
        1
  •  7
  •   Alex Martelli    15 年前

    与其自己深入了解细节,你可以 inspect 函数的签名——您可能需要 inspect.getargspec(cb) .

    我并不完全清楚你到底想如何使用这些信息以及你拥有的参数来正确地调用函数。为了简单起见,假设您只关心简单的命名参数,并且您希望传递的值在dict中 d

    args = inspect.getargspec(cb)[0]
    cb( **dict((a,d.get(a)) for a in args) )
    

    也许你想要更高级的东西,可以详细说明什么?

        2
  •  3
  •   S.Lott    15 年前

    这可能吗?

    def fnVariableArgLength(*args, **kwargs):
        """
        - args is a list of non keywords arguments
        - kwargs is a dict of keywords arguments (keyword, arg) pairs
        """
        print args, kwargs
    
    
    fnVariableArgLength() # () {}
    fnVariableArgLength(1, 2, 3) # (1, 2, 3) {}
    fnVariableArgLength(foo='bar') # () {'foo': 'bar'}
    fnVariableArgLength(1, 2, 3, foo='bar') # (1, 2, 3) {'foo': 'bar'}
    

    编辑 您的用例

    def foo(*args,*kw):
        x= kw.get('x',None if len(args) < 1 else args[0])
        y= kw.get('y',None if len(args) < 2 else args[1])
        z= kw.get('z',None if len(args) < 3 else args[2])
        # the rest of foo
    
    foo(1)         # should call foo(1, None, None)
    foo(y=2)       # should call foo(None, 2, None)
    foo(1,2,3,4,5) # should call foo(1, 2, 3)
    
    推荐文章