定义我自己的 None-like Python 常量
问题描述
我有一种情况,要求我阅读来自各种来源的数据库更新说明集合.所有源都将包含一个主键值,以便将更新应用于数据库的代码可以找到正确的记录.但是,这些文件会在报告的其他列中有所不同.
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 that applies the updates to the database can find the correct record. The files will vary, however, in what additional columns are reported.
当我阅读并创建我的更新说明时,我必须区分提供了列(例如,MiddleName)但为空的更新(意味着没有中间名并且该字段应更新为 NULL)和更新未包含 MiddleName 字段(意味着更新根本不应该触及中间名列).
When I read and create my update instructions I must differentiate between an update in which a column (for instance, MiddleName) was provided but was empty (meaning no middle name and the field should be updated to NULL) and an update in which the MiddleName field was not included (meaning the update should not touch the middle name column at all).
前一种情况(提供了列但没有值)似乎用 None 值适当地表示.然而,对于第二种情况,我想要一个 NotInFile 值",我可以像使用 None 一样使用它.
The former situation (column provided but no value) seems appropriately represented by the None value. For the second situation, however, I'd like to have a NotInFile "value" that I can use similar to the way I use None.
以下是正确的实现方式吗?
Is the correct way to implement this as follows?
NotInFile = 1
class PersonUpdate(object):
def __init__(self):
self.PersonID = None
self.FirstName = NotInFile
self.MiddleName = NotInFile
然后在另一个模块中
import othermod
upd = othermod.PersonUpdate()
if upd.MiddleName is othermod.NotInFile:
print 'Hey, middle name was not supplied'
解决方案
我看不出你的实现有什么特别的问题.但是,1
不一定是最佳标记值,因为它是 Cpython 中的缓存常量.(例如,-1+2 is 1
将返回 True
).在这些情况下,我可能会考虑使用哨兵对象实例:
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 还提供了一些其他命名常量,如果您认为合适,您可以使用它们:NotImplemented
和 Ellipsis
立即浮现在脑海.(请注意,我不建议您使用这些常量……我只是提供更多选项).
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).
相关文章