简体   繁体   中英

Is there an possible way to implement compact IF-statements in my python code?

Currently I have 3 If-statements done like this:

if filetype not in filetypes:
     print(f'  SKIPPED - WRONG FILETYPE: {filetype}')
     continue
elif 'comments' in meme_url or 'gallery' in meme_url:
     print('  SKIPPED - NOT A MEME')
     continue
elif meme_id in memes or meme_id in used_memes:
     print('  SKIPPED - USED')
     continue
            

These are sorting out non-valid images and I want to be able to traceback which 'filter' worked (currently it's done via print('problem')).

Nevertheless, this code 'smells' bad, so I am interested in more intelligent solution, if there is one. Thanks in advance.

You can do something like this:

def filter_by_name(filename, meme_url, used_memes):
    '''
    Returns True if filtered IN for more processing. False, if filtered out.
    '''

filters = [filter_by_name, filter_by_comment, filter_by_id]

filtered_out = False
for filter_function in filters:
    if not filter_function(filename, meme_url, used_memes):
        print(f'Not selected because did not pass through {filter_function}')
        filtered_out = True
        break
  
if filtered_out:
    continue
# Passed though all filters so process more

But as mentioned in comment, you are going to have function which have args which they don't even use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM