2
\$\begingroup\$

I have the following code to recursively list files within a directory:

from fnmatch import filter
from os      import path, walk

def files_within(directory_path):
  files_within = []
  for root, directory_path, files_path in walk(directory_path):
    for file_path in filter(files_path, "*"):
      files_within.append(path.join(root, file_path))
  return files_within

I want change it to avoid side affects. Is it possible?

I'm not using the glob because I'm using Python 2.5 because of a legacy code.

\$\endgroup\$
0

1 Answer 1

9
\$\begingroup\$

Your function could be a generator (which were introduced in Python 2.2). It should also expose the pattern for the filter as a parameter:

import os
import fnmatch

def files_within(directory_path, pattern="*"):
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for file_name in fnmatch.filter(filenames, pattern):
            yield os.path.join(dirpath, file_name)

if __name__ == "__main__":
    # You can simply iterate over the generator:
    for file_path in files_within("."):
        print file_path

    # If you absolutely need a list:
    file_list = list(files_within("../"))

    # Use the pattern parameter:
    text_files = list(files_within(".", "*.txt"))

I like to leave the names from os.walk the same as in the documentation, but this is a personal choice.

What is not quite a personal choice is the number of tabs per indentation level. Python's official style-guide, PEP8, recommends using always 4 spaces.

I also changed the way of the imports. Here it already becomes obvious why importing them like this is better (as far as readability goes). It is obvious that fnmatch.filter is from the module fnmatch and not the built-in filter.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ @FátimaAlves You're welcome. Even though I'm still not entirely sure what you mean by "side effects" in your question. Was it the overriding of the function name with the internal local variable? \$\endgroup\$
    – Graipher
    Commented Jan 19, 2017 at 12:57
  • \$\begingroup\$ I mean avoid reassign variables already assigned. \$\endgroup\$
    – FXux
    Commented Jan 19, 2017 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.