WARNING: The following question is asking for information concerning poor practices and dirty code. Developer discretion is advised.
Note: This is different than th
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.
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.