Here’s a function (credit to user Abbot, for providing it in another question)
def traverse(ftp):
level = {}
for entry in (path for path in ftp.nlst() if path not in ('.', '..')):
ftp.cwd(entry)
level[entry] = traverse(ftp)
ftp.cwd('..')
return level
Here’s what I don’t understand: When python enters the function it creates an empty dictionary (level). In the for loop, it stores a directory name as a key in the dictionary. as for the that key’s value, python enters the function again and searches for a directory and it becomes that key’s value.
But, how is the level dictionary remembering the values inside? I mean, shouldn’t it be reset/emptied everytime python enters the function?
No. Every “instance” of the function has its own copy of
leveland there are no side effects between the various copies oflevel.Take this folder tree:
Here’s the (simplified) execution flow when you call
ftponroot:ftp(root)creates an emptyleveldictionaryftp(root)enumerates subfolders:(home).ftp(root)picks the first subfolder and changes directory into it.ftp(root)setslevel[home]to the result offtpin the current folder.ftp(home)creates an emptyleveldictionaryftp(home)enumerates subfolders:(lyrae, badp).ftp(home)picks the first subfolder and changes directory into it.ftp(home)setslevel[lyrae]to the result offtpin the current folder.ftp(lyrae)creates an emptyleveldictionaryftp(lyrae)enumerates subfolders:().ftp(lyrae)is out of subfolders to parse and returnslevel.ftp(home)completes the assignment:levels = {'lyrae': {}}ftp(home)changes to the next folder.ftp(home)setslevel[badp]to the result offtpin the current folder.ftp(badp)creates an emptyleveldictionaryftp(badp)enumerates subfolders:().ftp(badp)is out of subfolders to parse and returnslevel.ftp(home)completes the assignment:levels = {'lyrae': {}, 'badp': {}}ftp(home)is out of subfolders to parse and returnslevel.ftp(root)completes the assignment:levels = {'home': {'lyrae': {}, 'badp': {}}}ftp(root)is out of subfolders to parse and returnslevel.