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 message 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 return a boolean result without the need for an if
statement. In your case os.path.exists
already returns a boolean so it's as simple as returning its result directly.
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" compared to using os.path.exists(file)
directly.
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)