相关疑难解决方法(0)

将所有参数和值传递给函数

我有一个Python函数,fetch_data它可以访问远程API,获取一些数据,然后将它包装在响应对象中.看起来有点像下面这样:

def fetch_data(self, foo, bar, baz, **kwargs):
    response = Response()
    # Do various things, get some data
    return response
Run Code Online (Sandbox Code Playgroud)

现在,响应数据可能会显示"我有更多数据,请使用递增page参数调用我以获得更多".因此,我基本上喜欢在响应对象中存储"方法调用"(函数,参数),因此我可以Response.get_more()查看存储的函数和参数,并再次调用函数(几乎)参数,返回一个新的Response

现在,如果fetch_data被定义为fetch_data(*args, **kwargs)我可能只是存储(fetch_data, args, kwargs)response.不过我有self,foo,barbaz担心-我可以只存储(fetch_data, foo, bar, baz, kwargs)但这是重复的非常不理想的量.

从本质上讲,我试图找出如何,在一个函数中,得到一个完全填充*args**kwargs,其中包括函数的命名参数.

python

46
推荐指数
7
解决办法
6万
查看次数

我什么时候应该使用varargs来设计Python API?

是否有一个很好的经验法则,你应该在你的API中更喜欢varargs函数签名而不是将迭代函数传递给函数?("varargs"是"可变参数"或"可变数量参数"的缩写;即*args)

例如,os.path.join有一个vararg签名:

os.path.join(first_component, *rest) -> str
Run Code Online (Sandbox Code Playgroud)

min允许:

min(iterable[, key=func]) -> val
min(a, b, c, ...[, key=func]) -> val
Run Code Online (Sandbox Code Playgroud)

any/ all只允许迭代:

any(iterable) -> bool
Run Code Online (Sandbox Code Playgroud)

python api variadic-functions

6
推荐指数
1
解决办法
3902
查看次数

如何在 Python 中以可重用的方式记录函数参数?

我发现自己多次编写这样的代码:

def my_func(a, b, *args, **kwargs):
    saved_args = locals() # Learned about this from http://stackoverflow.com/a/3137022/2829764
    local_var = "This is some other local var that I don't want to log"
    try:
        a/b
    except Exception as e:
        logging.exception("Oh no! My args were: " + str(saved_args))
        raise
Run Code Online (Sandbox Code Playgroud)

运行my_func(1, 0, "spam", "ham", my_kwarg="eggs")在 stderr 上给出以下输出:

ERROR:root:Oh no! My args were: {'a': 1, 'args': (u'spam', u'ham'), 'b': 0, 'kwargs': {'my_kwarg': u'eggs'}}
Traceback (most recent call last):
  File "/Users/kuzzooroo/Desktop/question.py", line 17, in my_func
    a/b …
Run Code Online (Sandbox Code Playgroud)

python logging arguments function

4
推荐指数
1
解决办法
3327
查看次数

Python:使用参数传递函数到内置函数?

像这个问题我想传递一个带参数的函数.但我想将它传递给内置函数.

例:

files = [ 'hey.txt', 'hello.txt', 'goodbye.jpg', 'howdy.gif' ]

def filterex(path, ex):
  pat = r'.+\.(' + ex + ')$'
  match = re.search(pat, path)         
  return match and match.group(1) == ex) 
Run Code Online (Sandbox Code Playgroud)

我可以使用带有for循环和if语句的代码,但它更短,使用filter(func,seq)可能更具可读性.但是,如果我理解正确,您使用过滤器的函数只接受一个参数,该参数是序列中的项目.

所以我想知道是否可以传递更多的论据?

python refactoring

1
推荐指数
1
解决办法
322
查看次数