如何与Enum和Enum34一起生活?

发布于 2025-02-06 01:55:24 字数 530 浏览 1 评论 0原文

我注意到Python上的Enum的行为不同。

首先,我很惊讶地注意到这是int

>>>import enum
>>>class Color(enum.Enum):
       red = 1

>>>Color.red
1

然后我意识到我已经安装了enum而不是enum34

$ sudo apt-get install python-enum34

现在,现在,结果是不同的:

>>>Color.red
<Color.red: 1>

我当前的应用程序是接受enum我以value.value获得枚举的值。当然,如果安装了错误的枚举,这将引起例外。

我该如何处理这个问题?

I noticed a different behaviour with enum on Python.

I was first surprised to notice the output for this was an int:

>>>import enum
>>>class Color(enum.Enum):
       red = 1

>>>Color.red
1

Then I realized I had enum installed instead of enum34:

$ sudo apt-get install python-enum34

And now, the result is different:

>>>Color.red
<Color.red: 1>

My current application is accepting enum types where I get the value of the enum with value.value. Of course this will raise an exception if the wrong enum is installed.

How can I deal with this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莫言歌 2025-02-13 01:55:24

猜测,看起来您有3.4枚举之前存在的enum软件包。 enum34之所以命名,是因为已经存在了先前的软件包。

enumenum34安装到同一位置,因此将它们共存并不容易 - 此外,它将使您的代码难以分发,就像枚举之一一样位于非标准位置。

一种可能性是使用 virtual envs - 那么您可以安装任何一个venv中的应用程序需要枚举。

As a guess, it looks like you had the enum package that existed before the 3.4 Enum came in to being. enum34 is so named because that previous package already existed.

Both enum and enum34 install to the same location, so making them co-exist is not easy -- plus it would make your code difficult to distribute as one of the enums would be in a non-standard location.

One possibility is to use virtual envs -- then you can install whichever enum is needed for the application in the venv.

零時差 2025-02-13 01:55:24

在另一个答案中调整 @jerry101的评论,这是我所掌握的:

def is_using_enum34(self):
    try:
        import enum
        return enum.__file__.__str__().endswith("__init__.pyc")
    except:
        return False
    return False

我注意到了:
enum34:enum .__文件__ == __ init __。pyc
枚举:enum

。在,可能对他人有帮助。

Adapting @Jerry101's comment in another answer, here's what I landed on:

def is_using_enum34(self):
    try:
        import enum
        return enum.__file__.__str__().endswith("__init__.pyc")
    except:
        return False
    return False

I noticed that for:

enum34: enum.__file__ == __init__.pyc

enum: enum.__file__ == enum.pyc.

I've not heavily used this and it's probably non-ideal, but it suits what I'm looking at and may be helpful for others.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文