我有许多表单函数:
def parse_file_1(file_name)
# do something generic
with open(file_name) as f:
for line in f:
# do some generic things with line
# do some things specific to parse_file_1 with line为了避免重复大量的代码,我使用一个装饰器重写了它:
def parse_file(parse_function):
def _parse_file(file_name):
# do something generic
with open(file_name) as f:
for line in f:
# do some generic things with line
parse_function(line)
return _parse_file
@parse_file
def parse_file_1(line):
# do some things specific to parse_file_1 with line这完全可以正常工作--这两个版本的功能完全相同,而且很容易编写这种形式的新函数,而不需要对通用代码进行任何复制和粘贴。
然而,装饰器parse_file更改了parse_file_1的签名,这混淆了PyCharm (它认为parse_file_1具有签名(line)而不是(file_name)),并且通常使确定parse_file_1的签名变得困难。
这种做法有多糟糕,以及(如果它很糟糕)有哪些好的替代方案(理想情况下不需要太多重复代码)?或者,让PyCharm知道parse_file_1的真实签名的方法可以消除我在当前情况下遇到的最大问题。
发布于 2018-08-15 19:31:48
我不会用装饰器来做这个的。相反,向其传递解析器函数的高阶生成器如何?
def parse_using(file_name, func):
with open(file_name) as f:
for line in f:
yield func(line)
def parse_foo_line(line):
return 'This line is very foo-ey: ' + line
parsed_foo = parse_using('foo.txt', parse_foo_line)
parsed_bar = parse_using('bar.txt', parse_bar_line) # etc...注意,这些函数是生成器,所以在迭代之前它们实际上不会解析任何东西(即使到那时,它们也只返回一次结果)。如果你想急切地解析一些东西,那就转换成一个列表。
parsed_foo = list(parse_using('foo.txt', parse_foo_line))https://stackoverflow.com/questions/51857799
复制相似问题