I try to avoid using classes in Python as much as possible; if I don't plan on building on it, I don't build it in the first place. It helps me avoid Java-like classes like FileDownloader(), when I could build download_file() instead.
That being said, I wanted to discuss getter and setter methods -- particularly getter methods. Instead of using class methods, I typically make them module methods (and use the module as others might use a class).
For example:
package/
|
| __init__.py
| constants.py
| main.py
| helpers.py
How this might be used:
#constants.py
import os
def get_default_directory():
return os.path.join(os.expanduser('~'), 'Desktop', 'files')
def get_server_name():
return '127.0.0.1'
def get_url_template(site, timezone):
...
And so on. This is the go here and change stuff if something changes area of the code.
For helpers.py, you might have some convenience functions that work well as one liners here and there, but duplicating them in each script might be a stretch while you're still formulating a final draft.
For instance, I had something like this, but ended up copying it into a second file later on:
def filename_from_path(path):
return os.path.split(path)[-1]
def trimext(filename):
return os.path.splitext(filename)[0]
def raw_filename(path):
return trimext(filename_from_path(path))
This replaced return os.path.splitext(os.path.split(path)[-1])[0], which ended up in a couple of places (and looked ugly).
main() simply holds all of my high level convenience functions, my "dumb functions", as they were. They just carry out a task, and make it take the least amount of keystrokes possible. Like a main method, but you have many different arrangements available to you.
#main.py
import constants
import helpers
def admin_dry_run(safe_mode=True):
do_main_a(safe_mode)
do_main_b(safe_mode)
do_main_c(safe_mode)
def dry_run(safe_mode=False):
if safe_mode:
#even this code could be defined in `helpers` to use
#the login credentials in `constants`, saving space here
if helpers.login(constants.get_credentials()):
do_main_a()
else:
do_main_b()
else:
do_main_c()
def do_main_a():
pass #...
Is this typical? Is there anyone who does this, or might be able to suggest a different approach to structuring programs that stretch across multiple files in a similar manner?