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

后端 未结 2 1249
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题