Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python style question: Support class as inner class?

I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass

Separate classes:

class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

like image 958
porgarmingduod Avatar asked Jun 16 '26 20:06

porgarmingduod


1 Answers

I would suggest

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

and put all this in a module of its own. The leading _ indicates that the utility classes are meant for internal use only (and for what it's woth, they won't get imported by from module import *; but I don't like this anyway).

Edit: Citing from PEP 8:

Classes for internal use have a leading underscore in addition.

like image 181
Sven Marnach Avatar answered Jun 19 '26 09:06

Sven Marnach