3

I have a script where and if-else condition is given, the if takes the user input and process that if a certain directory is empty and fills that certain directory and the else runs if the directory is already full.

if not any(fname.endswith('.csv') for fname in os.listdir(certain_dir)): 
    def process_user_input:
     ....code....
        return something
else:
    def do_process_on_the_full_directory:
     ....code....
        return something_else

so, if the directory is empty, the first condition becomes True and the first process happens, and then I have to run the script again to have the else condition run on the directory that is now full. My question is whether there is a better way of doing that, so I do not have to run the script twice to get what I want, e.g, if there is a way to add order (first, fulfill the first condition, second after the directory is filled run the second condition).

zara kolagar
  • 881
  • 3
  • 15

1 Answers1

3

We can leverage decorators1 here to enforce the invariant.

def fill_if_empty(func):
    def wrapper(*args, **kwargs):
        if YOUR_CONDITION_TO_CHECK_FOR_EMPTY_DIR:
            """
            fill empty directory here.
            """
            process_user_input()

        func(*args, **kwargs)
    return wrapper

@fill_if_empty
def do_process_on_the_full_directory():
    """
    Run some process on directory
    """
    pass

do_process_on_full_directory() 

1. Checkout this post to know more about decorators: How to make function decorators and chain them together?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • thank you very much for your reply. I just have one more question since I have not worked with decorators before, i am now wondering if I need to return something from the fill_if_empty function, where should I have that return statement? i am asking that because in my question the process_user_input function returns something – zara kolagar Oct 06 '21 at 07:11
  • @zarakolagar Decorator is nothing but a function taking a function as input and processing it and returns a function. The above is same as `fill_if_empty(do_process_on_the_full_directory)()`, so your decorator should return a function. You can read more about it in detail [here](https://stackoverflow.com/q/739654/12416453). – Ch3steR Oct 06 '21 at 07:18