Skip to content Skip to sidebar Skip to footer

Defining My Own None-like Python Constant

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 the code

Solution 1:

I don't see anything particularly wrong with your implementation. however, 1 isn't necessarily the best sentinel value as it is a cached constant in Cpython. (e.g. -1+2 is 1 will return True). In these cases, I might consider using a sentinel object instance:

NotInFile = object()

python also provides a few other named constants which you could use if it seems appropriate: NotImplemented and Ellipsis come to mind immediately. (Note that I'm not recommending you use these constants ... I'm just providing more options).


Solution 2:

If you want type-checking, this idiom is now blessed by PEP 484 and supported by mypy:

from enum import Enum

class NotInFileType(Enum):
    _token = 0

NotInFile = NotInFileType._token

If you are using mypy 0.740 or earlier, you need to workaround this bug in mypy by using typing.Final:

from typing import Final

NotInFile: Final = NotInFileType._token

If you are using Python 3.7 or earlier, you can use typing_extensions.Final from pip package typing_extensions instead of typing.Final


Post a Comment for "Defining My Own None-like Python Constant"