Comment

Comment by zo1

The article is incredibly misleading. Python Enums are way more powerful than what is showcased there.

First, rudimentary/basic enums are as simple as instance variables on a class and allow super-helpful IDE "auto-completion" that doesn't necessitate the use of magic-strings to at least "set" the enum. I've been using this ridiculously simple trick since 2.5 ten years ago. Magic-strings are bad, and even worse when you have a disparate code-base in a dynamically typed language. Example:

    class MyEnum(object):
        Pass = 1
        Fail = 2

    my_value = MyEnum. <-- at this point, the IDE gives you code-completion.

Second, real Enums added as a language-feature along with type-hinting are almost 100% on-par with statically typed languages. See:

    class MyEnum(Enum):
        Pass = 1
        Fail = 2

    def my_func(did_they_pass: MyEnum):
        if did_they_pass.Something:   # IDE / type-checker will go nuts here.
            print("Something")
Edit: Forgot the main point. Switch/case uses are only a small sub-set of the uses of Enums. So even basic/crappy enums are better than magic strings in a dynamically-typed language. Also, please don't use "list of strings" for enums in Python, there are much better ways to do that sort of thing that preclude unnecessary bugs popping up.
parent zo1 6 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton