发电机糖。
useless.pipes的Python项目详细描述
发电机周围的假黑糖。如果您编写嵌套for循环或嵌套函数a(b(c([1,2,3]))),这可能会有帮助。
基本上是这样的:
[1, 2, 3] | add(2) | list == [3, 4, 5]
其中
@worker def add(items, n): for i in items: yield i + n
最左边的参数总是来自左边的迭代器。其他参数表示绑定状态。使用此工作进程分为两步。
adder = add(2) # bind a state in a closure adder([1, 2, 3]) == [3, 4, 5] # apply an iterator
工人往往非常简单和简短,可重复使用和易于测试。
@worker def echo(items): for i in items: yield i echo = echo() # echo 'has' no state assert [1, 2, 3] | echo == [1, 2, 3]
有时候你可以做到这样:
filter_audio_files = fs.filter_by_ext(['.mp3']) @producer def folders_with_audio_files(path): for root, folders, filenames in os.walk(path): if any(filenames | filter_audio_files): yield root @worker def that_need_fix(paths): for path in paths: files = listdir(path) | filter_audio_files | join_path(path) | list dos_names = files | get_83DOS_name | list if files.sort() != dos_names.sort(): yield path that_need_fix = that_need_fix() # and the outermost commands in a script then look like this #give me all folders with mp3-files inside, e.g. print them to stdout folders_with_audio_files(root) #give me all folder that need a specific fix, aka dry-mode folders_with_audio_files(root) | that_need_fix #actually apply a fix to these folders folders_with_audio_files(root) | that_need_fix | apply_fix