My opinion is that it depends on level of encapsulation you want to achieve.
First case
Here you encapsulate work with files and an image conversion in a single function which is good. Now, think about SOLID principle, where is single responsibility here? It would be better to split this function in 2:
- get a stream
- convert an image stream to a desired format
Which is why I like option 2d better, however, let's go further.
Second case
In the second case you extract a logic of converting an image from a stream (No matter what is the source) which is good. Keep it that way.
Now, you list every file, open in and pass to the conversion function. Does it sound like a 3 separate actions? You can stop here if this code is not going to be reused.
If at any moment you want to reuse image conversion logic you can move it to a separate class or helper
for instance.
I see two better
/other options here:
Option #1
def convert_png_to_jpg(image):
# do something with my image
def convert_to_jpg(filepath):
# open file
convert_png_to_jpg(image)
all_images = os.listdir(path_to_images) for image in all_images:
convert_to_jpg(image) for image in all_images
Option #2
Extract converter and use it where it is needed.
class PngToJpgConverter(object):
def convert(image):
pass
def convert_from_file(filepath):
# open file
return self.convert(image)
converter = PngToJpgConverter()
all_images = os.listdir(path_to_images)
for image in all_images:
converter.convert_from_file(image)