by phyrex · 3y ago · 0 comments
But I understand that this is a very python answer.
1. It is not static. It can be configured, changed at runtime, etc
2. First order functions are very powerful as well
The real difference is that since it's not an object, "self" isn't in the function signature which to be fair can be annoying for a collection of stateless functions. So this is actually closer to a module.
@dataclass(frozen=True)
class MyArguments:
a: int,
b: str,
c: list = None
def func1(self):
...
def func2(self):
...
etc. You can also sprinkle in @property and functools things like @cached, @cached_property when desired. It also lets you create functions that transform MyArguments into different MyArguments.I agree with (2), but I'm not sure the pattern from the OP is a good example of using that power. It seems like using a language feature - mapping a string to an anonymous function - when a better one exists: defining named functions. Named functions can be looked up dynamically by name in python, and are (I think) generally more clear to a reader, especially with the standard documentation and type hints.
"Oh but you can replace this with a derived class", it's not as flexible (for example, mix and matching, etc)
> than to have to reason about runtime behavior to determine those things.
Sure if you only do CRUD you probably won't run into those cases. Math heavy, scientific code, simulations, etc might disagree
What do you mean by "mix and matching"? I feel like a concrete example might help me understand what you're thinking of in this thread.
> Sure if you only do CRUD you probably won't run into those cases. Math heavy, scientific code, simulations, etc might disagree
Ha, it's funny because I've recently started doing more math-y / scientific / simulation work in python, after a career spent mostly doing CRUD-y things in not-python, and I've never been more convinced that it is best to make code as statically legible as possible. It's hard enough to make sure the math and the algorithms are right, I don't want to also be reasoning through dynamic abstractions.
But again, maybe there's a concrete thing you're thinking of here that I'm not seeing!
Edit: I don't believe this is any slower, actually. It may even be marginally faster than a class, since a class adds some QOL features that will add a little overhead that would add a few branches to the code path.
But if you're worried about speed, don't use Python anyways.