简体   繁体   English

使tqdm等函数在Python中接受不同类型的参数

[英]Making tqdm and the like functions accept different types of parameters in Python

This is not specific to tqdm but a generic question about passing parameters to a function in Python.这不是 tqdm 特有的,而是关于在 Python 中将参数传递给函数的通用问题。 I want to achieve the following functionality without having to make copies of the entire-block under tqdm.我想实现以下功能,而不必在 tqdm 下制作整个块的副本。 Any help will be greatly appreciated.任何帮助将不胜感激。

if flag == True:
    with tqdm(dataloader, total=args.num_train_batches) as pbar:
else:
    with tqdm(dataloader) as pbar:

More specifically, can I pass parameters in a way like this?更具体地说,我可以像这样传递参数吗?

if flag == True:
    tqdm_args = dataloader, total=args.num_train_batches
else:
    tqdm_args = dataloader
with tqdm(tqdm_args) as pbar:

This is actually fairly simple to do, as it seems they thought of this when making Python.这实际上相当简单,因为他们似乎在制作 Python 时想到了这一点。 You can use Python's ternary operator to do this, condensing what you have above to a single line:您可以使用 Python 的三元运算符来执行此操作,将上面的内容压缩为一行:

with tqdm(dataloader, total=args.num_train_batches if flag else None) as pbar:
  # ...

Edit: to answer with your preferred method you mentioned, yes.编辑:用你提到的首选方法回答,是的。 That's also possible.这也是可能的。 If you put those arguments into a list (or dictionary, if you have keyword args) and then put a * (or ** for a dictionary) in front of the list's name when calling the function, it unpacks the list into a set of arguments.如果您将这些参数放入列表(或字典,如果您有关键字 args)中,然后在调用函数时在列表名称前放置一个* (或**表示字典),它会将列表解包为一组论据。

Example using a list:使用列表的示例:

if flag: # if flag is a boolean, putting "== True" does nothing
    tqdm_args = [dataloader, None, args.num_train_batches]
else:
    tqdm_args = [dataloader]
with tqdm(*tqdm_args) as pbar:
    # ...

Example with a dictionary:字典示例:

if flag:
  tqdm_kwargs = {"iterable": dataloader, "total": args.num_train_batches}
else:
  tqdm_kwargs = {"iterable": dataloader}
with tqdm(**tqdm_kwargs) as pbar:
  # ...

Happy to be of assistance!乐于助人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM