Quantcast
Channel: User Filip Milovanović - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 171

Answer by Filip Milovanović for Calling helper functions in a Python `__init__` function

$
0
0

You didn't provide a lot of detail, but this usually happens because you're trying to do too much in one class.

Now, if you don't want to clutter your class with helper functions, you could, as others have suggested on the StackOverflow main site, define your helpers outside of the class.

But, in this case, I'd personally move all of that initialization code out of the class - I'd create a plain data structure that I'd initialize using some free function before creating the class, then I'd pass that data structure into the class via a constructor parameter.

The class would then not be responsible for parameter initialization and the associated decision logic, except that it would perform some sanity checks (like that the argument is not None). It would be entirely focused on the specific task it was designed to do, once the values of the parameters have been decided on by something else.

In your original post on StackOverflow, you expressed your concern that "none of the code would be useful beyond initializing the class", but that's not really an issue. You don't necessarily separate things out because they'd be useful elsewhere, but because doing this lets you make your code cleaner and more readable. It lets you introduce meaningful names and divide work between parts of your codebase.

If what you really have are groups of attributes or parameters - e.g. (and I'm making these up) input params, output params, network params - you could create a number of such plain data classes, each letting you name and represent each group. It doesn't have to be a single data class.

Doing this could potentially simplify your initialization logic, as you'd only need to focus on the subset of values covered by each class. If it becomes simple enough, you could end up distributing it between the __init__ methods of each of these classes.


Viewing all articles
Browse latest Browse all 171

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>