我们有这篇文章: 我不确定,如果我做得恰当,在“+”之后就会打破一行, 下一个是由“()”人为地支撑,以便能够分解它。
代码本身背后的想法是py.test检查,如果文件夹已经准备就绪,文件是否也存在......以确保测试本身可以运行...
(一个问题是:“看看你如何做这些事情很有趣......”)
class TestFilewise():
def setup(self):
import os
self.fixture_dir = ( os.path.abspath(os.path.dirname(__file__)) +
"/fixtures/" )
assert os.access( self.fixture_dir, os.F_OK ), (
"Oops! the fixture dir should be here " + self.fixture_dir )
assert os.access( self.fixture_dir+"profiles-source1.csv", os.F_OK )
那么如何进行换行并保持最易读?
见How to break a line of chained methods in Python?但仍不确定......
答案 0 :(得分:1)
import os
class TestFilewise():
def setup(self):
self.fixture_dir = (os.path.abspath(os.path.dirname(__file__)) +
"/fixtures/")
assert os.access(self.fixture_dir, os.F_OK), \
"Oops! the fixture dir should be here " + self.fixture_dir
assert os.access( self.fixture_dir+"profiles-source1.csv", os.F_OK)
答案 1 :(得分:1)
imho,你根本不需要括号。
class TestFilewise():
def setup(self):
import os
self.fixture_dir = os.path.abspath(os.path.dirname(__file__)) \
+ "/fixtures/"
assert os.access( self.fixture_dir, os.F_OK ), \
"Oops! the fixture dir should be here " + self.fixture_dir
assert os.access( self.fixture_dir+"profiles-source1.csv", os.F_OK )
但事实上,我会使用os.path.join
制作更具可移植性的代码:
class TestFilewise():
def setup(self):
import os
self.fixture_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"/fixtures/")
assert os.access( self.fixture_dir, os.F_OK ), \
"Oops! the fixture dir should be here: '%s'" % self.fixture_dir
assert os.access(os.path.join(self.fixture_dir,
"profiles-source1.csv"), os.F_OK )
答案 2 :(得分:1)
在这种情况下,我会缩短os.path的名称 - 特别是因为它的命名空间仅限于该函数:
import os.path as op
另外,通常当我做断言时,如果我想提供自定义字符串,我会明确地提出它: ...
class TestFilewise():
def setup(self):
import os.path as op
self.fixture_dir = op.join(op.abspath(op.dirname(__file__)),"fixtures")
if not os.access( self.fixture_dir, os.F_OK ):
raise AssertionError("Oops! "
"the fixture dir should be here " + self.fixture_dir )
csvfile = op.join(self.fixture_dir,"profiles-source1.csv")
assert os.access(csvfile, os.F_OK )
当然,这只是我的偏好(assert
声明有一些优点。如果您认为它使您的代码更容易阅读,您可以自由地做任何您想做的事情(包括违反PEP 8)毕竟,该文件的第一行中有一条说,知道何时违反规则很重要。
最后,有时候你可以做的最好的事情就是使用一个适当命名的临时变量。
答案 3 :(得分:1)
使用更简单的名称可以缩短一些长行:
class TestFilewise():
def setup(self):
from os.path import abspath, dirname
from os import access, F_OK
fixture_dir = abspath(dirname(__file__)) + "/fixtures/"
self.fixture_dir = fixture_dir
exists = access(fixture_dir,F_OK)
assert exists, "Oops! the fixture dir should be here " + fixture_dir
assert access( fixture_dir+"profiles-source1.csv", F_OK )
这是否更容易阅读取决于读者。
答案 4 :(得分:1)
import os
class TestFilewise():
def setup(self):
self.fixture_dir = '%s/fixtures/' % \
os.path.abspath(os.path.dirname(__file__))
assert os.access(self.fixture_dir, os.F_OK), \
'Oops! the fixture dir should be here: %s' % self.fixture_dir
assert os.access(
'%sprofiles-source1.csv/' % self.fixture_dir, os.F_OK
)