dimanche 3 décembre 2023

Composability: Iterator vs Lambda

I am having trouble understanding the concept of 'good' functional composability. Assume the following approaches for deleting files with a specific extension:

Using Lambda functions:

def traverse_tree(
        temp_storage: Local, extensions: List[str], is_raw: bool, operation: Callable
):
    for folder_path, subfolders, filenames in os.walk(temp_storage.root_path(is_raw)):
        for filename in filenames:
            base, ext = os.path.splitext(filename)
            if ext in extensions:
                file_path = os.path.join(folder_path, filename)
                operation(file_path)

def clear_temp(
        temp_storage, extensions: List[str], is_raw
):
    traverse_tree(temp_storage=temp_storage, extensions=extensions, is_raw=True, operation=lambda x: os.remove(x))

Using an iterator:

def traverse_tree(
        temp_storage, extensions: List[str], is_raw
):
    for folder_path, subfolders, filenames in os.walk(temp_storage.root_path(is_raw)):
        for filename in filenames:
            base, ext = os.path.split(filename)
            if ext in extensions:
                file_path = os.path.join(folder_path, filename)
                yield file_path


def clear_temp(
        temp_storage: Local, extensions: List[str], is_raw: bool
):
    for path in traverse_tree(temp_storage, extensions, is_raw):
        os.remove(path)

Is one approach favored over the other in terms of modularity and ease of debugging? If so, can you give an example where one approach objectively results in less flexibility?

Thanks,

Aucun commentaire:

Enregistrer un commentaire