Creating a common function module

I have big projects with dozens of different modules. I have many commonly used functions that I use in many places in my project. For example:

  • Checking if a string contains Hebrew characters
  • Create a random string of 8 letters
  • Guessing binary image data mime type
  • Convert HTML documents
  • Etc ...

My questions:

  • Is it possible to put all these functions in a specific module that will be loaded from each code file?
  • What name should this module have? common.py ?
  • My code is divided into packages . Usually to place a file in the root folder and download a file that is outside the package area?
+7
source share
3 answers

Variations on util or utils seem common. Personally, if I have packages like myproj.foo , myproj.bar , etc., I tend to have a package myproj.util with a module for each scope of intention (maybe myproj.util.http for web assistants, myproj.util.data for manipulation data structure, etc.). Such helpers are more likely to be reused than your main code, and pure division into modules (even if you end up with single-class or single-function modules) makes reuse easier.

+7
source

Based on my knowledge for:

1st: if these functions, say, have 1000 / 100s lines / functions, the module will become more and more awkward and difficult to read and edit. The package would be the right choice for him, as it facilitates fine-grained categorization and slightly quick module loading, as delnan correctly said, along with many other many other benefits that I currently don't know about.

Now, say, your project at the whole development stage will need only 10-20 such functions, then I propose to make one module.

2: utilities , followed by specific modules with their specific names foo.py Or just utilities.py

3rd: I would appreciate a good response from others.

PS: rule of thumb. Try to keep utility functions independent of project logic and as general as possible. This way your functions will be reused elsewhere without dependency problems.

Edit 1-2: Improving the accuracy of the first answer

+4
source

We put them in the core/ module from the root of the project, each in its own file (provided that they have nothing in common). We chose the name core simply because it uses Django, and that is the specific logic in the expression from myproject.core import rand_string .

For generality in smaller modules, for example. Django, we put the functions in the utils.py file in the root of the application, although I am not completely satisfied with this solution ...

+1
source

All Articles