11

Trying to use an enum in Python 3.7.3, getting the following error. Already tried to install - and uninstall - enum34, but it still does not work. Did all the operations in a virtual environment (as the error shows).

Is there anything else I can do to fix this (except using another enum implementation as shown in this question)?

#enum import:
from enum import Enum

# enum definition:
class Status(Enum):
    on: 1
    off: 2

# enum utilisation (another class, same file):
self.status = Status.off

# error:
File "C:\dev\python\test\venv\lib\enum.py", line 349, in __getattr__
AttributeError(name) from None
AttributeError: off
evilmandarine
  • 4,241
  • 4
  • 17
  • 40

2 Answers2

31

The correct syntax for defining an enum is:

class Status(Enum):
    on = 1
    off = 2

Not on: 1.

jwodder
  • 54,758
  • 12
  • 108
  • 124
7

In your definition, use = to assign values to the attributes, not :.

# enum definition:
class Status(Enum):
    on = 1
    off = 2
c0x6a
  • 427
  • 1
  • 6
  • 14
  • That's it but you're just too late sorry :/ – evilmandarine Jun 10 '19 at 19:43
  • 2
    Could you add an explanation of why the OP's original syntax was not an error? – Ethan Furman Jun 10 '19 at 20:10
  • @EthanFurman what? why do you say it "was not an error"? Actually it was a syntax error; you use `=` to assign values, not `:`. – c0x6a Jun 10 '19 at 20:43
  • 1
    Not in 3.7 -- it creates annotations, which is why `Status` was empty. – Ethan Furman Jun 10 '19 at 20:49
  • @EthanFurman I'm new to Python. Looked for annotations after your comment. Are you talking about annotations such as "on: int = 1, off: int = 2"? If yes, why does "on: 1" not generate an error as 1 is not a type such as int or str? – evilmandarine Jun 10 '19 at 21:22
  • 1
    Heh -- that's for you to research and educate us! If you want to, of course. Depending on the depth of your answer I'm happy post a bounty of between 100 - 500 reputation. – Ethan Furman Jun 10 '19 at 21:36
  • @EthanFurman I was just trying to educate myself and understand your comment, sorry to have bothered you. – evilmandarine Jun 11 '19 at 08:54
  • @EthanFurman, that's not how `annotations` are supposed to be used, you have to use data types, not values ¯\\_(ツ)_/¯ – c0x6a Jun 11 '19 at 16:00
  • @supafly: Oops! I thought I was talking to @c0x6a. My apologies! The short answer to your question is that annotations are there to support static-type checkers, such as MyPy, so Python itself does nothing with the information given except storing it in an `__annotations__` attribute. – Ethan Furman Jun 11 '19 at 16:29
  • @EthanFurman no worries :) thank you! (in the meanwhile I've been downvoted, don't really know why but no worries there too... was working late after hours of json, didn't see my silly error and ended up learning about annotations :) – evilmandarine Jun 11 '19 at 19:56