保持80个字符的利润与声明长?

2024-04-29 18:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

什么是pythonic的方式来让PEP-8-ify,比如用语句:

with tempfile.NamedTemporaryFile(prefix='malt_input.conll.', dir=self.working_dir, mode='w', delete=False) as input_file, tempfile.NamedTemporaryFile(prefix='malt_output.conll.', dir=self.working_dir, mode='w', delete=False) as output_file:
    pass

我可以这样做,但是由于tempfile I/o没有使用with语句,所以它会在with之后自动关闭吗?那是Python吗?地址:

intemp = tempfile.NamedTemporaryFile(prefix='malt_input.conll.', dir=self.working_dir, mode='w', delete=False)

outtemp = tempfile.NamedTemporaryFile(prefix='malt_output.conll.', dir=self.working_dir, mode='w', delete=False)

with intemp as input_file,  outtemp as output_file:
    pass

或者我可以用斜杠:

with tempfile.NamedTemporaryFile(prefix='malt_input.conll.',
dir=self.working_dir, mode='w', delete=False) as input_file, \
tempfile.NamedTemporaryFile(prefix='malt_output.conll.', 
dir=self.working_dir, mode='w', delete=False) as output_file:
    pass

但这是否符合规定?那是Python吗?你知道吗


Tags: selffalseinputoutputprefixmodeasdir
2条回答

PEP-8实际上给出了两种类似情况的示例:

示例1(看起来最适用,因为它使用了with语句):

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

例2:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):

看起来,斜杠是一种允许的处理方法(但如果将文件参数括在括号中,则最终是不必要的)。你知道吗

PEP 0008 does say it's okwith行使用反斜杠。你知道吗

Backslashes may still be appropriate at times. For example, long, multiple with -statements cannot use implicit continuation, so backslashes are acceptable.

虽然建议缩进,但行应该是这样的:

with tempfile.NamedTemporaryFile(prefix='malt_input.conll.',
      dir=self.working_dir, mode='w', delete=False) as input_file, \
      tempfile.NamedTemporaryFile(prefix='malt_output.conll.', 
      dir=self.working_dir, mode='w', delete=False) as output_file:
    pass

建议您将它缩进到下面的代码块中一个明显不同的空间量,这样可以更清楚地看到with行的结束和块的开始。你知道吗

但是,如果将参数括在括号中,则实际上不需要使用斜杠

with (tempfile.NamedTemporaryFile(prefix='malt_input.conll.',
      dir=self.working_dir, mode='w', delete=False)) as input_file, (
      tempfile.NamedTemporaryFile(prefix='malt_output.conll.', 
      dir=self.working_dir, mode='w', delete=False)) as output_file:
    pass

当然,这取决于你准确的句子安排,你的里程数可能会因在一行末尾加括号是否比反斜杠好而有所不同。你知道吗

相关问题 更多 >