Search code examples
pythonpython-3.xconventions

Splitting code into modules (conventions)


So I've been searching for a bit and couldn't find anything on Google or PEP discussing this.
I am doing a project with tkinter and I had a file, that is part of a project, that was only 200 lines of code (excluding all the commented out code). While the entire file was related to the GUI portion of the project, it felt a bit long and a bit broad to me.
I ended up splitting the file into 4 different files that each has its own portion of the GUI.
Basically, the directory looks like this:

project/
        guiclasses/
                   statisticsframe.py
                   textframes.py
                   windowclass.py
        main_gui.py
        ...

statisticsframe has a class of a frame that shows statistics about stuff.
textframes holds 3 classes of frames holding textareas, one of them inherits Frame, the others inherit the first one.
windowclass basically creates the root of the window and all the general initialization for a tkinter GUI.
main_gui isn't actually the name but it simply combines all the above three and runs the mainloop()

Overall, each file is now 40-60 lines of code.

I am wondering if there are any conventions regarding this. The rule of thumb in most languages is that if you can reuse the functions/ classes elsewhere then you should split, though in Python it is less of a problem since you can import specific classes and functions from modules.

Sorry if it isn't coherent enough, nearly 3AM here and it is simply sitting in the back of my head.


Solution

  • I'm not familiar with tkinter, so my advice would be rather broad.

    You can use any split into modules which you feel is better, but

    • as readability counts try making names coherent and do not repeat yourself: guiclasses - your enire progarm is about GUI, and there obviously classes somewhere, why repeath that in a name? imagine typing all that in in import, make it meaningful to type
    • flat structure is better than nested, three modules do not have to go to submodule
    • best split is across layers of abstraction (this is probably hardest and specific to tkinter)
    • anything in a module shoudl be rather self-sufficient and quite isolated from other parts of the program
    • modules should make good entitites for unit testing (eg share same fixtures)
    • can you write an understandable docstring for a module? then it's a good one.
    • try learning by example, I often seek wisdom for naming and package structure in Barry Warsaw mailman, maybe you can try finding some reputable repo with tkinter to follow (eg IDLE?).

    From purely syntatic view I would have named the modules as:

    - <package_name>
       - baseframe
       - textframe
       - window
       - main