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 ?

4
  • Actually, what are you trying to achieve here? Commented Jul 26, 2018 at 7:03
  • I'am adding/deleting some template files in django from my Django Applications. @JerinPeterGeorge Commented Jul 26, 2018 at 7:05
  • Ok, Is there any problem with adding/deleting? Commented Jul 26, 2018 at 7:08
  • I can see these changes in my file explorer. But not getting reflected in my Django app Commented Jul 26, 2018 at 7:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I never knew about this. I'am relatively new to python and lacks a strong base. Thanks a lot...@PavelMinenkov

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.