How to create a second None in Python? Making a singleton object where the id is always the same

后端 未结 2 1250
孤街浪徒
孤街浪徒 2021-01-13 20:11

WARNING: The following question is asking for information concerning poor practices and dirty code. Developer discretion is advised.

Note: This is different than th

相关标签:
2条回答
  • 2021-01-13 21:06

    I'm going to answer part X, not part Y:

    I have configuration classes that holds onto values of parameters. Some of these parameters can take None as a valid type. However, I want these parameters to take particular default values if no type is specified.

    ...

    For instance:

    def add_param(name, value=NoParam):
        if value is NoParam:
            # do some something
        else:
            # do something else
    

    The proper way to test whether or not value was defined by the caller is to eliminate the default value completely:

    def add_param(name, **kwargs):
        if 'value' not in kwargs:
            # do some something
        else:
            # do something else
    

    True, this breaks some introspection-based features, like linters that check whether you're passing the right arguments to functions, but that headache should be much, much less than trying to bend the identity system over backwards.

    0 讨论(0)
  • 2021-01-13 21:18

    Is there anything I can do to achieve this same behavior with pickling?

    Yes.

    class _NoParamType(object):
        def __new__(cls):
            return NoParam
        def __reduce__(self):
            return (_NoParamType, ())
    
    NoParam = object.__new__(_NoParamType)
    

    To take it even further: is there anything I can do to ensure that only one instance of NoParam is ever created?

    Not without writing NoParam in C. Unless you write it in C and take advantage of C API-only capabilities, it'll always be possible to do object.__new__(type(NoParam)) to get another instance.

    0 讨论(0)
提交回复
热议问题