Call function without optional arguments if they are None

前端 未结 9 2060
自闭症患者
自闭症患者 2020-12-29 02:00

There\'s a function which takes optional arguments.

def alpha(p1=\"foo\", p2=\"bar\"):
     print(\'{0},{1}\'.format(p1, p2))

Let me iterat

9条回答
  •  悲哀的现实
    2020-12-29 02:34

    Another possibility is to simply do alpha("FOO", myp2 or "bar"), but that requires us to know the default value. Usually, I'd probably go with this approach, but I might later change the default values for alpha and this call would then need to be updated manually in order to still call it with the (new) default value.

    Just create a constant:

    P2_DEFAULT = "bar"
    
    def alpha(p1="foo", p2=P2_DEFAULT):
         print('{0},{1}'.format(p1, p2))
    
    

    and call the function:

    alpha("FOO", myp2 or P2_DEFAULT)
    

    If default values for alpha will be changed, we have to change only one constant.

    Be careful with logical or for some cases, see https://stackoverflow.com/a/4978745/3605259

    One more (better) use case

    For example, we have some config (dictionary). But some values are not present:

    config = {'name': 'Johnny', 'age': '33'}
    work_type = config.get('work_type', P2_DEFAULT)
    
    alpha("FOO", work_type)
    

    So we use method get(key, default_value) of dict, which will return default_value if our config (dict) does not contain such key.

提交回复
热议问题