Having issues with a recursive function that should be relatively simple to do, but can`t seem to get right.
I have a folder structure with folders that can contain other folders, images or files. Associated with each folder there are permissions. I want to have my function recursively build a list of the permissions that are associated with each folder.
I have a function has_read_permission(request) that returns True if the folder has permissions and False if not
I have built a function like so:
def get_child_perms(self, folder, request, perm_list):
# Folder contains other folders
if folder.get_children():
# For every sub-folder
for subfolder in folder.get_children():
return perm_list.append(self.get_child_perms(subfolder, request, perm_list))
else:
# If folder doesn't have sub-folders containing folders
return [folder.has_read_permission(request)]
I keep getting None
Given folders like so:
Folder (allowed) - Wont check this one
|_First Folder (allowed)
| |_First sub Folder (restricted)
| | |_File
| | |_File
| | |_Image
| |__Second Sub Folder (allowed)
|_Second Folder (allowed)
Then running get_child_perms() would return
[True,False,True,True]
or even
[True, [False, True], True]
EDIT
Disregard edit -> asked other question Python Recursive function missing results
Changed abit,
def get_child_perms(self, folder, request, perm_list):
if folder.get_children():
for subfolder in folder.get_children():
perm_list.append(self.get_child_perms(subfolder, request, perm_list))
return perm_list
else:
return [folder.has_read_permission(request)]
getting:
[[True], [...], [True], [...], [...], [True], [True], [True], [True], [True], [True], [True], [True], [...], [True], [...]]
Admin
-Folder 1
- Files
-Folder 2
- Files
-Folder 3
- Files
-Folder 4
- SubFolder 1
-SubSubFolder 1
- Files
- Files
- SubFolder 2
- SubSubFolder 2
- Files
- Files
-Folder 5
- SubFolder 3
- Files
- SubFolder 4
- Files
- SubFolder 5
-Files
- Files
-Folder 6
- Files
-Folder 7
- SubFoler 6
- Files
- Files
-Folder 8
- Files
forloop's body be executed iffolder.get_children()returns and empty iterable?returninside the loop? That will make it exit after at most one iteration.None), you should mark an answer accepted. Ask a new question if you have one, but you can't just keep editing this one until the function works just how you want it.