mardi 28 septembre 2021

Best way to execute instruction and set variables before any method call in Python class

I need to set a number of environment variables and class properties before any other command is executed like for example:

def __init__(self):
  os.environ["HOST"] = os.uname()[1]
  self._home = os.environ["HOME"]
  self._storage = f'{self._home}/my-storage'
  self._service_names = None
  self._requirements_file = None

I also need to read some files and set some more variables.

I thought to include them in the "init" function but I am thinking that this might make the class initialization step too slow.

Is this recommended doing file reads and other potentially time consuming operations in init? What other mechanism does Python offer to ensure that as set of instruction is executed before a class method is executed? I could put these operations in a decorator function maybe?

Aucun commentaire:

Enregistrer un commentaire