I'll disagree with the others and say yes. For me, I have had better success putting each class in its own file (module). But there are exceptions so let me explain with an example.
If you have a class Foo, then put it in a file called Foo.py, with the following sections:
- Imports
- This is where you pull in dependencies.
- Examples:
import math
, from Bar import *
- Globals
- This is where you define the external interface to your module, which are all of the symbols that are visible outside of this module.
- Example:
__all__ = ['Foo']
- This is also where you can define global variables (bad) and global constants (good). These globals need not be exported; they can be made global merely to simplify the code.
- Example:
PI = 3.14159
means that you can write PI
, whereas if you defined it inside class Foo then you would need to write Foo.PI
.
- Functions
- This is where you define all top-level functions that are relevant to class Foo, but don't belong in the class Foo namespace. These are probably rare since classes allow both
@staticmethods
and inner classes.
- Example:
def print_foo(foo): print(foo)
- Classes
- Example:
class Foo(object): pass
Sometimes you will want to place more than one class in the same module. You should do this whenever two or more classes are conceptually related to the point where you would almost always use them together and never independently. This is the exception, not the norm. In this case add all of the class names to the __all__
global.
Finally, for every module Foo.py, there should be a corresponding unit test module called testFoo.py.