如何向Typer传递列表参数?遇TypeError错误求助
解决Typer列表参数默认值报错问题
问题原因
当给Typer的typer.Argument指定List[int]类型时,Typer会自动设置nargs=-1(允许接收任意多个位置参数),但这种模式下不支持直接设置default参数——因为nargs=-1的参数默认行为是空列表,和你指定的默认值冲突,所以抛出TypeError: 'default' is not supported for nargs=-1。
解决方案
方案1:用typer.Option替代typer.Argument(推荐)
typer.Option支持为列表类型设置默认值,同时允许通过命令行参数覆盖:
import typer from typing import List def typer_main( channels: List[int] = typer.Option([1, 2, 3], help='List of channels'), ): for channel in channels: print(channel)
- 运行默认命令
python main.py,会输出1、2、3 - 自定义参数时用
--channels前缀:python main.py --channels 4 5 6,输出4、5、6
方案2:手动处理Argument的默认值
如果必须使用位置参数(不需要--前缀),可以将参数设为Optional[List[int]],默认值设为None,在函数内部补充默认逻辑:
import typer from typing import List, Optional def typer_main( channels: Optional[List[int]] = typer.Argument(None, help='List of channels'), ): channels = channels or [1, 2, 3] for channel in channels: print(channel)
- 运行
python main.py时,channels为None,自动替换为[1,2,3] - 传参时直接输入位置参数:
python main.py 7 8,输出7、8
内容的提问来源于stack exchange,提问作者roman
相关产品推荐
相关产品推荐

