简体   繁体   English

存储和使用自己的状态码的大多数pythonic方式

[英]Most pythonic way to store and use own status codes

That's a really dumb question for sure (and perhaps a bit opinion-based), but how do I create an enum-like object that stores things like error codes, which are constant and to be accessed later in code? 当然,这确实是一个愚蠢的问题(也许有点基于意见),但是我如何创建一个枚举式对象,该对象存储诸如错误代码之类的东西,这些东西是恒定的,以后可以在代码中访问?

It occurs to me that there are four choices: 在我看来,有四个选择:

1) one status code - one variable 1)一个状态码-一个变量

STATUS_NEW = 0
STATUS_PENDING = 1
STATUS_DONE = 2
STATUS_ERROR = -1

if some_object.status == STATUS_NEW:
    print 'this object is pretty fresh!'

This doesn't look good to me. 这对我来说不好看。

2) a dictionary containing all status codes with its name as the key: 2)包含所有状态代码的词典,其名称为键:

STATUS = {'new': 0, 'pending': 1, 'done': 2, 'error': -1}

if some_object.status == STATUS['new']:
    print 'you got the idea.'

This looks uglier, but still, one object is better than several ones. 这看起来很丑,但是,一个对象胜于多个对象。

3) a named tuple looks even better, but it's it looks much worse to me at its initialization: 3)一个命名的元组看起来更好,但在初始化时对我来说却差很多:

STATUS = namedtuple('Status', ['error', 'new', 'pending', 'done'])
STATUS = STATUS(error=-1, new=0, pending=1, done=2)

if some_object.status == STATUS.new:
    print 'looks prettier than using dict!'

4) Using a class: 4)使用一个类:

class Status:
    NEW = 0
    PENDING = 1
    DONE = 2
    ERROR = -1

if some_object.status == Status.NEW:
    pass

Am I missing something? 我想念什么吗? What is more encouradged? 还有什么鼓励呢?

Thanks in advance! 提前致谢!

Enums in python are designed exactly for this. python中的枚举正是为此目的而设计的。

from enum import Enum

class STATUS(Enum):
    NEW = 0
    PENDING = 1
    DONE = 2
    ERROR = -1

Enums are available starting from 3.4. 枚举从3.4开始可用。 If you aren't so lucky pypi has a backport available. 如果您不是很幸运,那么pypi可以使用backport。

For python < 3.4 I personally prefer 4th one, but... 对于python <3.4,我个人更喜欢第四名,但是...

if some_object.status == Status.NEW:
    pass

Don't do that. 不要那样做 You may want to return error code for external tools, but in all-Python environment you should use exceptions. 您可能想返回外部工具的错误代码,但是在全Python环境中,应该使用异常。 Different error codes are just different exception raised. 不同的错误代码只是引发了不同的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM