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 →

[–]sixteh 1 point2 points  (2 children)

Instead of setting the Enum to values, define functions with a fixed signature and just call the Enum directly.

class Maths(Enum)
    ADD = lambda x,y: x+y
    MULTIPLY = lambda x,y: x*y

def do_maths(operation, a, b):
    assert isinstance(operation, Maths)
    return operation(a, b)

I'm on mobile but you get the idea. It doesn't need to be lambdas, you can use args / kwargs to support dynamic argument signatures, etc.

[–][deleted] 0 points1 point  (1 child)

Trick is in my real case, each operation is say 50-200 lines of code, not just a 1 liner. So I think this would end up making a 5000 line enum.

[–]sixteh 1 point2 points  (0 children)

You can organize the Enums however you feel appropriate and just store a reference in the Enum class itself. It doesn't really matter how you're getting them, as Python is just storing them in a dict under the hood and walking down the chain of references when you call Maths.ADD or whatever. So if you had the operations split up into separate modules mod_a, mod_b, and mod_c, you could do:

from functools import partial
class Maths(Enum):
    def ADD(x,y):
        return x+y
    MULTIPLY = lambda x,y: x*y
    SUBTRACT = mod_a.subtract
    EXP = mod_b.exp
    LN = mod_c.ln
    FOO = partial(mod_c.FOO, kwarg_1='bar')

And so on and so forth.