0

I have the following function that gives me the list of files(complete path) in a given list of directories:

from os import walk
from os.path import join

# Returns a list of all the files in the list of directories passed
def get_files(directories = get_template_directories()):
    files = []
    for directory in directories:
        for dir, dirnames, filenames in walk(directory):
            for filename in filenames:
                file_name = join(dir, filename)
                files.append(file_name)
    return files

I'am adding some files to the template directories in Django. But this function always return the same list of files even though some are added/deleted in the run time. These changes are reflected only when I do a server restart. Is that because of some caching that os.walk() performs or is it required that we need to restart the server after adding/removing some files ?

deltaforce
  • 524
  • 1
  • 8
  • 25

1 Answers1

2

It is not django problem, your behaviour is result of python interpreter specific:

Default arguments may be provided as plain values or as the result of a function call, but this latter technique need a very big warning. Default values evaluated once at start application and never else.

I' m sure this code will solve your problem:

def get_files(directories = None):
    if not directories:
        directories = get_template_directories()
    files = []
    for directory in directories:
        for dir, dirnames, filenames in walk(directory):
            for filename in filenames:
                file_name = join(dir, filename)
                files.append(file_name)
    return files

You can find same questions on Stackoverflow Default Values for function parameters in Python

deltaforce
  • 524
  • 1
  • 8
  • 25
Pavel Minenkov
  • 368
  • 2
  • 9
  • 1
    I never knew about this. I'am relatively new to python and lacks a strong base. Thanks a lot...@PavelMinenkov – deltaforce Jul 26 '18 at 09:04