Home > Software engineering >  How to create a python function that runs as soon as its file is imported?
How to create a python function that runs as soon as its file is imported?

Time:11-13

I am trying to make a module for personal uses, but I want to make it so as soon as I import it, it will run a function. Is there any way to do this. (preferably use the threading module as I already am using it)

CodePudding user response:

Within the module, call the function

def run_this_first():
   # write your code here
   pass

run_this_first()

Every time the module is imported, it will run run_this_first()

CodePudding user response:

That is exactly what should happen if you call the function needed inside the file you are importing without using

if __name__ == "__main__":

In other words, inside your file that you are importing, you should use something like:

# define your function
def fun():
   pass

# call your function (without the typical if __name__ == "__main__")
fun()

  • Related