声明长期保留80个字符?

alv*_*vas 7 python pep8 with-statement

什么是PEP-8-ify的pythonic方式,例如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
Run Code Online (Sandbox Code Playgroud)

我可以这样做,但由于临时文件i/o没有with声明,它是否会在with后自动关闭?那是pythonic吗?:

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
Run Code Online (Sandbox Code Playgroud)

或者我可以使用斜杠:

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
Run Code Online (Sandbox Code Playgroud)

但PEP8是否符合要求?那是pythonic吗?

Sup*_*Man 4

PEP 0008 确实表示可以在一行中使用反斜杠with

反斜杠有时仍然是合适的。例如,长的多个 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
Run Code Online (Sandbox Code Playgroud)

建议您将其缩进与以下代码块明显不同的空间量,以便更清楚 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
Run Code Online (Sandbox Code Playgroud)

当然,这确实取决于您的确切句子排列,并且您的里程可能会因行尾有括号是否比反斜杠更好而有所不同。