Python tips and tricks — make code more flexible
I am starting a serie of small posts on Python tips and tricks originating from my own working experience.
My first tip is about writing code flexible and reusable at the first time. Each time you design a new method or component a good practice is to write a method or component which will be easily adaptable and re-usable in future.
Let me tell about my story. We are working with my collegues on OCR and price tag recognition. We have own server with object detection API. Working on my current task I deal with sending HTTP requests with images to our API. Let’s say I have a batch of 10 images and I need to run price tag detection on these images. Images are quite large (order of MBs). We have a timeout set to 30 sec. on server but processing of one such large image takes up to several minutes. So the sending a request with ten images will fail on definition.
I have decided to send a request with one image so processing all the batch requires 10 requests. The method implementing API request takes a list of images. Here is a call of this method
api_response = self.api_client.custom_endpoint_processing(self.samples, self.suffix_url)
My first ideas was to implement a method performing API request like that
def call_recognition_api(self, sample):
api_response = self.api_client.custom_endpoint_processing([sample], self.suffix_url)
We simply put a sample to an empty list and pass the list as the first argument to the API function. If we think about future usage of this method we can see the shortage of this method. In future we will likely deal with images of different size and the limit won’t be probably a problem — it will be possible to tune the batch size to send to API. So better solution would be to make the method more generic and open
def call_recognition_api(self, samples):
api_response = self.api_client.custom_endpoint_processing(samples, self.suffix_url)
And call this method with a list including the only image at that moment.
In future you can easily pass more samples to this method. That makes the code more flexible and reusable.
That’s it. My advice is to think in advance how your code will be used in future. See you and stay in touch. Enjoy the Python programming.