How to check whether optional function parameter is set

前端 未结 10 1363
傲寒
傲寒 2020-12-02 15:06

Is there an easy way in Python to check whether the value of an optional parameter comes from its default value, or because the user has set it explicitly at the function ca

10条回答
  •  伪装坚强ぢ
    2020-12-02 15:40

    I've seen this pattern a few times (e.g. library unittest, py-flags, jinja):

    class Default:
        def __repr__( self ):
            return "DEFAULT"
    
    DEFAULT = Default()
    

    ...or the equivalent one-liner...:

    DEFAULT = type( 'Default', (), { '__repr__': lambda x: 'DEFAULT' } )()
    

    Unlike DEFAULT = object(), this assists type-checking and provides information when errors occur -- frequently either the string representation ("DEFAULT") or the class name ("Default") are used in error messages.

提交回复
热议问题