获取该关键字参数实际传递给一个Python方法 [英] Getting the the keyword arguments actually passed to a Python method

查看:160
本文介绍了获取该关键字参数实际传递给一个Python方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有明确的关键字ARGS做梦一个Python的方法:

I'm dreaming of a Python method with explicit keyword args:

def func(a=None, b=None, c=None):
    for arg, val in magic_arg_dict.items():   # Where do I get the magic?
        print '%s: %s' % (arg, val)

我想要得到的只有这些参数调用者实际上传递到方法,就像 ** kwargs ,但我不希望调用者是一个字典能够通过任何旧随机指定参数时,不像 ** kwargs

I want to get a dictionary of only those arguments the caller actually passed into the method, just like **kwargs, but I don't want the caller to be able to pass any old random args, unlike **kwargs.

>>> func(b=2)
b: 2
>>> func(a=3, c=5)
a: 3
c: 5

所以:有这样的咒语?就我而言,我碰巧能够比较反对它的默认每个参数来查找不同的人,但是这是一种不雅当你有9个参数变得乏味。对于加分,提供了一个咒语,可以告诉我,即使在调用者传递一个关键字参数指定的默认​​值:

So: is there such an incantation? In my case, I happen to be able to compare each argument against its default to find the ones that are different, but this is kind of inelegant and gets tedious when you have nine arguments. For bonus points, provide an incantation that can tell me even when the caller passes in a keyword argument assigned its default value:

>>> func(a=None)
a: None

调皮!

修改的(词汇)的函数签名必须保持不变。这是一个公共API的一部分,而明确的关键字args来主要价值在于它们的文献价值。只是为了让事情变得有趣。 :)

The (lexical) function signature has to remain intact. It's part of a public API, and the primary worth of the explicit keyword args lies in their documentary value. Just to make things interesting. :)

推荐答案

我被丢理论的装饰灵感来自善良,以后玩它关于有点与此想出了:

I was inspired by lost-theory's decorator goodness, and after playing about with it for a bit came up with this:

def actual_kwargs():
    """
    Decorator that provides the wrapped function with an attribute 'actual_kwargs'
    containing just those keyword arguments actually passed in to the function.
    """
    def decorator(function):
        def inner(*args, **kwargs):
            inner.actual_kwargs = kwargs
            return function(*args, **kwargs)
        return inner
    return decorator


if __name__ == "__main__":

    @actual_kwargs()
    def func(msg, a=None, b=False, c='', d=0):
        print msg
        for arg, val in sorted(func.actual_kwargs.iteritems()):
            print '  %s: %s' % (arg, val)

    func("I'm only passing a", a='a')
    func("Here's b and c", b=True, c='c')
    func("All defaults", a=None, b=False, c='', d=0)
    func("Nothin'")
    try:
        func("Invalid kwarg", e="bogon")
    except TypeError, err:
        print 'Invalid kwarg\n  %s' % err

其中打印此:


I'm only passing a
  a: a
Here's b and c
  b: True
  c: c
All defaults
  a: None
  b: False
  c: 
  d: 0
Nothin'
Invalid kwarg
  func() got an unexpected keyword argument 'e'

我很高兴这一点。更灵活的方法是通过您要使用的装饰属性的名称,而不是硬编码为'actual_kwargs',但这是说明该解决方案最简单的方法。

I'm happy with this. A more flexible approach is to pass the name of the attribute you want to use to the decorator, instead of hard-coding it to 'actual_kwargs', but this is the simplest approach that illustrates the solution.

嗯,Python是好吃。

Mmm, Python is tasty.

这篇关于获取该关键字参数实际传递给一个Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆