On Thu, 2011-10-20 at 14:37 +1000, Nick Coghlan wrote:
candidate_dirs = sorted(candidate_dirs, key=get_mtime) given: candidate_dirs = next(filter_walk(base_dir,
dir_pattern=dir_filter, depth=0)).subdirs candidate_dirs = (subdir for subdir in candidates if not any(d in subdir for d in dirs_to_ignore)) def get_mtime(path): stat_path = os.path.join(base_dir, path) return os.stat(stat_path).st_mtime
Notice how the comment from the original version becomes redundant in the second version? It's just repeating what the actual header line right below it says, so I got rid of it. In the original version it was necessary because there was no indentation in the code to indicate that this was all just different stages of one internal calculation leading up to that final step to create the sorted list.
I think you are loosing me, I just don't see some of the things you've mentioned before in this. And I don't see any advantage in the second version over the first.
It's fairly common to build up a result by a chain of results that modifies the result of the previous result, with a final result. And it's not too uncommon to reuse the same name as you go, so...
If the given statement set the name of the ongoing calculation, and the suite following it was a series of expressions with no right hand side assignment. Your routine would look as follows.
# Generate list of candidate directories # sorted by modification time.
def get_mtime(path): stat_path = os.path.join(base_dir, path) return os.stat(stat_path).st_mtime
candidate_dirs given: = next(filter_walk(base_dir, dir_pattern=dir_filter, depth=0)).subdirs
= (subdir for subdir in candidate_dirs if not any(d in subdir for d in dirs_to_ignore))
= sorted(candidate_dirs, key=get_mtime)
Each expression would give candidate_dir a new value and avoid duplicating the result name on each line. It also might be possible to generate optimized byte code as the result could stay on the stack until the block is exited.
I could also see this used in a command window...
... = 10 ... += 20 ... -= 10 ...
This does put the item of interest up front like you want, and it also reduces repetition is calculations, but it's quite a different concept overall.