Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are inner-classes unpythonic?

Tags:

python

My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic.

What do people here think? Are inner-classes something which are more appropriate to Java etc than Python?

NB : I don't think this is a "subjective" question. Surely style and aesthetics are objective within a programming community.


Related Question: Is there a benefit to defining a class inside another class in Python?

like image 398
interstar Avatar asked Nov 29 '22 20:11

interstar


2 Answers

This may not deserve a [subjective] tag on StackOverflow, but it's subjective on the larger stage: some language communities encourage nesting and others discourage it. So why would the Python community discourage nesting? Because Tim Peters put it in The Zen of Python? Does it apply to every scenario, always, without exception? Rules should be taken as guidelines, meaning you should not switch off your brain when applying them. You must understand what the rule means and why it's important enough that someone bothered to make a rule.

The biggest reason I know to keep things flat is because of another philosophy: do one thing and do it well. Lots of little special purpose classes living inside other classes is a sign that you're not abstracting enough. I.e., you should be removing the need and desire to have inner classes, not just moving them outside for the sake of following rules.

But sometimes you really do have some behavior that should be abstracted into a class, and it's a special case that only obtains within another single class. In that case you should use an inner class because it makes sense, and it tells anyone else reading the code that there's something special going on there.

  • Don't slavishly follow rules.
  • Do understand the reason for a rule and respect that.
like image 142
dwc Avatar answered Dec 06 '22 09:12

dwc


"Flat is better than nested" is focused on avoiding excessive nesting -- i.e., seriously deep hierarchies. One level of nesting, per se, is no big deal: as long as your nesting still respects (a weakish form of) the Law of Demeter, as typically confirmed by the fact that you don't find yourself writing stuff like onething.another.andyet.anotherone (too many dots in an expression are a "code smell" suggesting you've gone too deep in nesting and need to refactor to flatten things out), I wouldn't worry too much.

like image 34
Alex Martelli Avatar answered Dec 06 '22 09:12

Alex Martelli