4 ms·
class Foo(object): def run(self, context): ... Objects with only a single method to run it are already built into Python, they are the functions. def
by remram 2y ago
class Foo(object):
def run(self, context): ...
Objects with only a single method to run it are already built into Python, they are the functions.
def foo(context): ...
- porridgeraisin 2y agoBut how can one survive without a daily dose of Utterly Brain Damaged Abstractions?
- itherseed 2y agoThe advantage of the original approach is that later, when you need it, you can just add more methods to a class that are private to them. In your approach, if you need a new function, you add it at the global level, which can totally be fine for one or two functions, but with any more you end up with a bunch of functions all at the same level that is no longer obvious the dependency between them.
- heisenzombie 2y agoIf you want a function that's private to a function in Python you _could_ also do: def foo(context): def bar(x): return x*2 baz = bar(context) ... This is particularly idiomatic for higher order functions, but I think it can be useful for other things if used with restraint. But if you have functions that only need to be called from one calling function then I why not just inline the code and eschew having a function at all. Long function bodies for the win!
- notfish 2y agoDon’t do this, it makes it a huge pain to test bar(). When you write the initial code to figure out bar, just throw that code in a unit test so you can run it any time. Stop throwing tests away!
- heisenzombie 2y agoYes, perhaps I wasn’t clear — I’m advocating for just the inlined version, not the nested function in the general case. The nested function is, I think, fine when it’s so tiny it’s not worth unit testing (like, it-could-have-been-a-lambda small) or when bar is returned by foo (ie foo is higher order), in which case you can test the return value. Apart from that… restraint!
- remram 2y agoYou can do that with a function too, make it a class with a __call__. If you need it, which you won't for this kind a script.
- muixoozie 2y agoLol Reminds me of Brain Will's https://www.youtube.com/watch?v=QM1iUe6IofM https://www.youtube.com/watch?v=QM1iUe6IofM he has a series basically ranting about this. One of them he goes into examples simplifying needlessly abstract code.