Organizing Python classes in modules and / or packages

I like the Java convention of having one public class for each file, even if sometimes there are good reasons to put more than one public class in one file. In my case, I have alternative implementations of the same interface. But if I put them in separate files, I would have redundant names in the import statements (or misleading module names):

import someConverter.SomeConverter 

whereas someConverter will be the name of the file (and module) and someConverter name of the class. It looks pretty unflattering to me. To put all the alternative classes in a single file, you get a more meaningful import statement:

 import converters.SomeConverter 

But I'm afraid that the files will become quite large if I put all the related classes in one module file. What is Python best practice? Is one class for each file unusual?

+50
python module class package
01 Oct 2018-10-10
source share
2 answers

Many of them are personal preferences. Using python modules, you have the option to save each class in a separate file and still allow import converters.SomeConverter (or from converters import SomeConverter )

Your file structure might look something like this:

 * converters - __init__.py - baseconverter.py - someconverter.py - otherconverter.py 

and then in the __init__.py file:

 from baseconverter import BaseConverter from otherconverter import OtherConverter 
+52
01 Oct 2018-10-0120:
source share

The Zach solution breaks down into Python 3. Here is a fixed solution.

Many of them are personal preferences. Using python modules, you have the option to save each class in a separate file and still allow import converters.SomeConverter (or from converters import SomeConverter )

Your file structure might look something like this:

 * converters - __init__.py - baseconverter.py - someconverter.py - otherconverter.py 

and then in the __init__.py file:

 from converters.baseconverter import BaseConverter from converters.otherconverter import OtherConverter 
+35
Nov 06
source share



All Articles