Defining my own None-like Python constant

前端 未结 3 949
独厮守ぢ
独厮守ぢ 2020-12-04 02:42

I have a situation in which I\'m asked to read collections of database update instructions from a variety of sources. All sources will contain a primary key value so that t

3条回答
  •  臣服心动
    2020-12-04 02:58

    No, using the integer one is a bad idea. It might work out in this case if MiddleName is always a string or None, but in general the implementation is free to intern integers, strings, tuples and other immutable values as it pleases. CPython does it for small integers and constants of the aforementioned types. PyPy defines is by value for integers and a few other types. So if MiddleName is 1, you're bound to see your code consider it not supplied.

    Use an object instead, each new object has a distinct identity:

    NotInFile = object()
    

    Alternatively, for better debugging output, define your own class:

    class NotInFileType(object):
        # __slots__ = () if you want to save a few bytes
        def __repr__(self):
            return 'NotInFile'
    
    NotInFile = NotInFileType()
    del NotInFileType # look ma, no singleton
    

    If you're paranoid, you could make it a proper singleton (ugly). If you need several such instances, you could rename the class into Sentiel or something, make the representation an instance variable and use multiple instances.

提交回复
热议问题