简化的标志定义。
easy-flags的Python项目详细描述
这个nano项目的目标是通过添加一些新功能为argparse提供简单的替代方案:
- 易于定义
- 类型检查(使用静态类型检查工具)
- 可重用性
安装
pip install easy_flags
基本示例
食物比
fromeasy_flagsimportSimpleConfigclassMyConfig(SimpleConfig):int_val=4bool_val=Truewith_doc=0.4,'some docs'# type: floatwithout_default=None,int,'another docs'# type: boolif__name__=='__main__':# command line arguments will be parsed after ::define callc=MyConfig().define().print()print('bool_val:',c.bool_val)
运行:
$ python foo.py + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bool_val : True | int_val : 4 | with_doc : 0.4 | without_default : None + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool_val: True Process finished with exit code 0 $ python foo.py -h usage: foo.py [-h] [--bool_val | --no-bool_val] [--int_val INT_VAL] [--with_doc WITH_DOC] [--without_default WITHOUT_DEFAULT] optional arguments: -h, --help show this help message and exit --bool_val bool, default: True --no-bool_val --int_val INT_VAL int, default: 4 --with_doc WITH_DOC float, default: 0.4 - some docs --without_default WITHOUT_DEFAULT int, default: None - another docs
替代定义
fromeasy_flagsimportConfig,IntField,BoolField,FloatFieldclassMyConfig(Config):int_val=IntField(4)bool_val=BoolField(default=True)with_doc=FloatField(0.4,'some docs')without_default=IntField(doc='another docs')
可重用性
fromeasy_flagsimportConfigclassModelConfig(Config):layers=4time_steps=256cell_size=256dropout=1.0# same as model config + additional parametersclassTrainingConfig(ModelConfig):lr=0.001epochs=10000dropout=0.9# change parent arg
文档字符串
如果要为字段添加帮助消息(如果使用--help标志运行脚本,则将显示该消息),则需要在标志的默认值之后添加该消息:
classExampleConfig(BaseConfig):foo=5.0,'Some float field.'bar='field with only default docstring'
./script.py --help usage: test_base.py [-h][--bar BAR][--foo FOO] optional arguments: -h, --help show this help message and exit --bar BAR String field, default='field with default docstring'. --foo FOO Float field, default=5.0. Some float field.
布尔值
配置名称中指定的布尔标志将目标值设置为True,前缀为“no-”的同一标志将值设置为False
classExampleConfig(BaseConfig):cache=Truef=False
./script --cache -f # cache=True, f=True ./script --no-cache --no-f # cache=False, f=False
短标志名
如果标志名仅由一个字母组成,则可以用一个破折号而不是两个破折号指定。
classExampleConfig(BaseConfig):e=100,'number of epochs'b=True
./train.py -e 42 -b # also valid with two dashes ./train.py --e 42 --b ./train.py --e 42 --no-b
指定元组的类型
classExampleConfig(BaseConfig):lr=0.001,'learning rate'conf=ExampleConfig()conf.define()
在上面的示例中,预定义的conf.lr显然不是float,类型检查之后的一些静态检查程序将发出警告,指出它们希望某个函数的参数是float,但得到的却是tuple。幸运的是,我们可以通过添加带有适当after define type的特殊注释来帮助ide:
classExampleConfig(BaseConfig):lr=0.001,'learning rate'# type: float