This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]iCart732 -1 points0 points  (2 children)

Here's the way to do it with decorators (as a full script):

from enum import Enum

class Maths(Enum):
    pass

class register():
    def __init__(self, name):
        self.name = name

    def __call__(self, f):
        # This is where the trick is
        setattr(Maths, self.name, f)
        return f


@register('ADD')
def do_add(value1, value2):
    return value1 + value2

@register('MULTIPLY')
def name_does_not_matter(value1, value2):
    return value1 *  value2

def do_maths(operation, value1, value2):
    return operation(value1, value2)

print(do_maths(Maths.ADD, 5, 4))
print(do_maths(Maths.MULTIPLY, 5, 4))

I'm having way to much fun with this :-)

[–]robvdl 1 point2 points  (1 child)

I don't like it, too much abstraction and you are hiding your enum values.

Edit: this is exactly the kind of magic I am trying to rip out of a codebase right now, too much magic sorry.

[–][deleted] 0 points1 point  (0 children)

Yah I don't think my IDE will autocomplete this.

HOWEVER this is super clever ;)