I have the following if statement and I feel it could be made simpler to read by breaking the terms up into their own named variables.

if os.path.isfile(os.path.join(dirname, 'file.json')) \
or (os.path.isdir(os.path.join(dirname, 'folder'))
and os.listdir(os.path.join(dirname, 'folder')) != []):

So it would look something like this:

file_exists = os.path.isfile(os.path.join(dirname, 'file.json'))
directory_exists = os.path.isdir(os.path.join(dirname, 'folder'))
directory_not_empty = os.listdir(os.path.join(dirname, 'folder')) != [])
if file_exists or (directory_exists and directory_not_empty):

The problem with this is that in the first implementation the and can short circuit and if it does the directory_not_empty term is not evaluated, which could cause an error. When they are broken into variables they are eagerly executed at assignment. My solution to this was to use a lambda to cause the directory_not_empty term to simulate lazy assignment.

file_exists = os.path.isfile(os.path.join(dirname, 'file.json'))
directory_exists = os.path.isdir(os.path.join(dirname, 'folder'))
directory_not_empty = lambda:os.listdir(os.path.join(dirname, 'folder')) != [])
if file_exists or (directory_exists and directory_not_empty()):

I think this looks quite elegant however the pep8 standard doesn't like assignment of lambdas and using a one line function definition feels very clunky here. The call on directory_not_empty and not the others also feels clunky. Is there an elegant way of doing this?


2 Answers 2


If you want to do it this way, I would make the directory_not_empty variable handle both the check for the presence of the directory and check if its non-empty. Also, if the long lengths are annoying then I would put the directory in its own variable.

my_dir = os.path.join(dirname, 'folder')
directory_not_empty = os.path.isdir(my_dir) and (os.listdir(my_dir) != [])

Using pathlib, if feasible, may also help readability, by itself or in combination with the accepted answer:

# setup
from pathlib import Path
dirname = Path(dirname)
# Dropped into original code
if (dirname / "file.json").is_file() \
or ((dirname / "folder").is_dir()
and (dirname / "folder").iterdir() != []):
# Dropped into the accepted answer
my_dir = dirname / "folder"
directory_not_empty = my_dir.is_dir() and (my_dir.iterdir() != [])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.