我有一个这样的with-statement:
from tqdm import tqdm
with tqdm(documents) as progress_bar:
for document in documents:
if [...]:
process(document)
progress_bar.update()process()是另一个函数,在该函数中,我希望将日志记录设置为上下文中是否存在tqdm实例(从上面的代码中调用)(从其他地方调用)。在伪码中,例如:
def process(document):
if <tqdm in context>:
progress_bar.write("processing")
else:
logging.info("processing")我能否从父作用域中动态地查找和访问with-context (在本例中由tqdm提供)?多么?
contextlib documentation不提供访问with-context的(直截了当的)方式。
到目前为止,我找到的解决方法是将progress_bar对象作为可选参数传递给process(),并在可用时使用它。但是,仅为此目的更改函数似乎是多余的。
一般情况下,或者tqdm是否提供了一种处理这个问题的模式?
背景的更新
这里的用例是,在这里的实际代码中,我有一个函数调用的连接。实际上,process()更复杂,并调用各种其他函数。这些可能会记录输出,如果可用的话,输出应该转到progress_bar.write()。
如果调用堆栈中的叶函数无法从根函数访问with-context,则需要将progress_bar对象向下传递到调用树的所有级别。
发布于 2020-01-17 09:01:23
总结评论意见:
with-context (而且不应该有)。def process(document, writer: Callable[[str], Any] = logging.info):
writer("processing")
[...]为了写入tqdm实例而不是记录器,您可以这样调用process():
from tqdm import tqdm
with tqdm(documents) as progress_bar:
for document in documents:
if [...]:
process(document, writer=progress_bar.write)
progress_bar.update()https://stackoverflow.com/questions/59752441
复制相似问题