The Pythonic way of organizing modules and packages

空扰寡人 提交于 2019-11-28 15:58:43

Think in terms of a "logical unit of packaging" -- which may be a single class, but more often will be a set of classes that closely cooperate. Classes (or module-level functions -- don't "do Java in Python" by always using static methods when module-level functions are also available as a choice!-) can be grouped based on this criterion. Basically, if most users of A also need B and vice versa, A and B should probably be in the same module; but if many users will only need one of them and not the other, then they should probably be in distinct modules (perhaps in the same package, i.e., directory with an __init__.py file in it).

The standard Python library, while far from perfect, tends to reflect (mostly) reasonably good practices -- so you can mostly learn from it by example. E.g., the threading module of course defines a Thread class... but it also holds the synchronization-primitive classes such as locks, events, conditions, and semaphores, and an exception-class that can be raised by threading operations (and a few more things). It's at the upper bound of reasonable size (800 lines including whitespace and docstrings), and some crucial thread-related functionality such as Queue has been placed in a separate module, nevertheless it's a good example of what maximum amount of functionality it still makes sense to pack into a single module.

If you want to stick to your one-class-per-file system (which is logical, don't get me wrong), you might do something like this to avoid having to refer to automobile.Automobile:

from automobile import Automobile
car = Automobile()

However, as mentioned by cobbal, more than one class per file is pretty common in Python. Either way, as long as you pick a sensible system and use it consistently, I don't think any Python users are going to get mad at you :).

If you are coming from a c++ point of view, you could view python modules akin to a .so or .dll. Yeah they look like source files, because python is scripted, but they are actually loadable libraries of specific functionality.

Another metaphor that may help is you might look python modules as namespaces.

In a mid-sized project, I found myself with several sets of closely related classes. Several of those sets are now grouped into files; for example, the low-level network classes are all in a single network module. However, a few of the largest classes have been split out into their own file.

Perhaps the best way to start down that path from a one-class-per-file history is to take the classes that you would normally place in the same directory, and instead keep them in the same file. If that file starts looking too large, split it.

cobbal

As a vague guideline: more than 1 class per file is the norm for python

also, see How many Python classes should I put in one file?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!