1

So, I've got a library which can read a certain file (file layout is out of my control). These files have versions, and with each version more features are added. I've got Enums that represent some features. Now with the latest update, new entries should be added to the Enum. But, I want to be able to give the user a warning (or exception) when they try to use newer features in older versions.

I figured decorators might be the way to go, marking certain values & functions like: @from_version('1.40') or something like it. I've never created my own decorators so I'm not too familiar with them.

One final problem with this, the version of the file isn't globally available. (I can't add something static-ish because multiple files should be able to be opened at once). So I'm not even sure if decorators are the way to go.

Now I tried adding a decorator to an Enum entry, but that didn't work:

import enum
>>> def hello_world(f):
...     def decorated(*args, **kwargs):
...         print('Hello World!')
...     return decorated
... 
>>> class A(enum.Enum):
...     @hello_world()  # Tried with and without ()
...     ABC = 1
  File "<input>", line 3
    ABC = 1
    ^
SyntaxError: invalid syntax

So I'm wondering how I can add this to an enum, I also tried adding a property in an enum so I can add the decorator to that, but even adding the property didn't work...

TL;DR

How do I add my own decorator to a specific enum entry? I expected it to look like this:

class EnumClass(Enum):
    @from_version('1.40')
    ENTRY = 0

Thanks in advance for any help!

Kerwin Sneijders
  • 750
  • 13
  • 33

1 Answers1

1

What you want is in a separate answer, but to explain the problem you are having -- decorators are only usable with functions and classes (def and class) and cannot be used with attributes (things like ABC = 1.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237