Run a function when importing module in Python

Viewed 68

What I want to achieve: I have a function (object/module/etc) that allows me to run a model. This model requires a few parameters, so I want to have them in a config file rather than pass all through the code. So what I want is to have a config file created automatically when my module is imported. Is it possible in python? Can I have some pointers on where to start please?

1 Answers

All the code in a python file is run when its imported. If you have

def f():
  print("ran")

print("imported")

Then when you import it it will print imported This is also why you sometimes see if __name__=="__main__": In some files. The code in that block is only run if the file is run as main not imported. However creating files in a predetermined location may be bad UX, so if you want other people to use your library id think of a better solution.

Generally you can just put code at top level of a module and it will run.

Related