Python: passing flags to functions

前端 未结 6 2112
清酒与你
清酒与你 2021-02-09 12:27

For a long time i have been trying to figure out what is the best way to pass flags to python functions. The most straightforward way is something like:

def func         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-09 13:17

    Some Python standard libraries use this:

    re.match(pattern, str, re.MULTILINE | re.IGNORECASE)
    

    You can tweak this approach by using *args:

    my.func(a, b, c, my.MULTLINE, my.IGNORECASE)
    

    I would really recommend going with flag1=True:

    • it is readable
    • flag name is checked at compile time (unless **kwargs is used)
    • you can use flag=1 and flag=0 instead of True and False to reduce the noise
    • you can temporarily change LONG_FLAG_NAME_YOU_DONT_REMEMBER=True to False without retyping the long name when you will need to change back

提交回复
热议问题