Python is the best place for common functions

I am writing a jar application, and I discovered that I have a ton of common utility functions.

Here are examples of the type of functions that I consider common utility functions:

def make_hash(): return defaultdict(make_hash) def file_read(filename): with open(file_name_, 'r') as f: return f.read() def file_write(filename, data): with open(filename, 'w') as f: f.write(data) 

I was thinking about combining these functions into a separate module. However, I am curious if I have the following problems:

  • There are several unique features that guarantee a separate module. that is, the file_read and file_write functions described above can go into the file.py module, however, from its two functions, I feel that this can be excessive.
  • In my application, I use these functions 2-3 times per function, so I move under the mask creating these utility functions to help me save some lines of code and hopefully makes me more efficient.

Question: - What will be the pythonic way of grouping common utility functions? Should I create a separate module? Curious what others are doing to organize this type of code.

+6
source share
3 answers

I do not think that it has much to do with Python, it is rather a design decision.

Only for these lines I will not create a separate module; however, if you use it 2 to 3 times, I would not copy the code. If you later want to change something, you need only one change that supports functionality.

Also, the methods seem very versatile, so you can easily use them in other projects later.

And I assume that you want to make them static ( @static_method ).

I basically do group utility classes by type, i.e. in your case, one file for dictionaries (with 1 method) and one for the file (having 2 methods). More methods will be added later, but the functionality is grouped by type / usage.

+2
source

In python, we have something called Package (a regular folder with an empty file called __init__.py ), which is used to place all your modules in such a way that we create somesort line spacing.

your application can access its own namespace using.

for example have the following files

 MyPackage/__init__.py (empty) MyPackage/webapp.py (your web application) MyPackage/utils.py (generic utilities) 

and in webapp.py you can have something like this

 from .utils import * 

or list them one at a time

 from .utils import file_read, file_write 

note the dot prefix before utils

0
source

There is something you can do to reduce the number of module files while maintaining the subcategory of your modules .. Create multi-level module functions: myModule.Hash <. >. MyModule.FileIO <>

This way you can import individual components to your liking.

0
source

Source: https://habr.com/ru/post/943867/


All Articles