R1703:The if statement can be replaced with 'return bool(test)'
I write a function to check if the file exists, but pylint throws a message:"R1703:The if statement can be replaced with 'return bool(test)". What the mes开发者_运维知识库sage means? In addition, how to write a pytest script to test my code below?
def is_file_valid(file):
"""
check if input file exits
:param file: file
:return: True/False
"""
if os.path.exists(file):
return True
else:
return False
I've tried if ...==1: but it seems not work.
def is_file_valid(file):
"""
check if input file exits
:param file: file
:return: True/False
"""
if os.path.exists(file)==1:
return True
else:
return False
For pytest script, I write...
file_test = 'test.txt' # actually this file does not exist.
def test_is_file_valid(file_test):
# test is_file_valid()
assert os.path.exists(file_test) is False, "No this file"
os.remove(file_test)
pytest only shows the following message:
ERROR test/unit/test_io_utils.py::test_is_file_valid
Do you guys have any ideas how to figure it out?
The suggestion means that your function could be rewritten to directly return the result of os.path.exists
because that function already returns a boolean.
def is_file_valid(file):
"""
check if input file exits
:param file: file
:return: True/False
"""
return os.path.exists(file)
However, whether the function in this state actually makes sense, is in my opinion questionable because I don't see any "added value".
As for how to test it... create (or not) a file in Pytest's temporary folder:
def test_is_file_valid_true(tmp_path):
file = tmp_path / 'file.txt'
file.touch()
assert is_file_valid(file)
def test_is_file_valid_false(tmp_path):
file = tmp_path / 'file.txt'
assert not is_file_valid(file)
精彩评论