0

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?

  • Is comparing a list to an integer what looks clunky to me. – Goyo Apr 17 at 8:43
  • 2
    Ow! My eyes! Use import os.path already. – candied_orange Apr 17 at 14:52
1

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) != [])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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