Xartab
Xartab

Reputation: 37

It there a way to self-initialise a function outside of a class?

I have this piece of code that needs to run each time I execute the program (it empties a folder):

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

ClearOutputFolder()

I was wondering if there's a less awkward way of automatically calling a function than defining it and then calling it later.

I've tried to put an __init__ outside of a class, just to see, but as expected it acted like a normal function and needed to be called.

import os

def __init__():
    delete_stuff                # this runs but does nothing on its own

It's not a matter of life and death, obviously, I was just curious if there's a simple solution that I'm not aware of.

Thanks.

EDITED for clarification

Upvotes: 1

Views: 39

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36682

if you call the function in a if __name__ == '__main__ block, it will automatically execute upon launching the package.

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

def main():
    ClearOutputFolder()


if __name__ == '__main__':

    main()

if you want the call to happen upon importing, you can do like this:

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

ClearOutputFolder()   # this call is executed upon importing the package

Upvotes: 1

Related Questions