定义自己的无类Python常量 [英] Defining my own None-like Python constant

查看:77
本文介绍了定义自己的无类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为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 省略号立即浮现在脑海。 (请注意,我不建议您使用这些常量...我只是提供更多选项)。

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).

这篇关于定义自己的无类Python常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆