utils.py
I have written the following statements on slack today in a more project-related manner and thought this could make a small dev-tip post as well. Here goes πͺ
You basically donβt ever want to create a file called utils.py
, or helpers.py
(you also donβt want core.py
or common.py
but letβs focus on utils for now).
There are a few reasons to that:
π putting things into utils.py makes it a bag full of everything from simple datetime calculations to sophisticated validators and Class mixins
π utils is a nondescriptive name so nobody including you will know what has been put there in two weeks and more importantly where to look if someone has already written that util you are looking for (because they might put it in itβs proper place)
π there is always a better place with a better name than utils (examples below)
How to approach the topic in an already operating project:
π itβs good to move functions out from utils.py
to their corresponding utils/proper_module.py
each time you find an example and talk with your team about the whole purpose of moving that out
π if something is more generic than a simple module in your Django app / python module, you can move it higher in directory structure to the more generic utils/proper_module.py
file. So generally speaking if you want utils in your project, just make it more structured. I prefer the name helpers more than utils, but no strings attached here - itβs more important to keep consistency within the project, not looking at your own personal preferences.
Some examples of moves from utils.py
:
π amount_of_cat_food_validator
β helpers/validators
π CatPurrAwareMixin
β helpers/mixins
π calculate_days_until_christmas
β helpers/datetime
π a few topic related files can reside in their own directory, so form related modules (like new field types) will reside in helpers/forms/
Interesting related reads:
π http://deviq.com/naming-things/
π https://github.com/erikras/react-redux-universal-hot-example/issues/808
π https://softwareengineering.stackexchange.com/a/175190