Pass Variable On Import

后端 未结 8 1409
轻奢々
轻奢々 2020-12-16 09:37

Let\'s say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done

8条回答
  •  佛祖请我去吃肉
    2020-12-16 10:14

    I had to do something similar for my project. If you don't want to rely on the calling script to run the initialization function, you can add your own Python builtin which is then available to all modules at runtime.

    Be careful to name your builtin something unique that is unlikely to cause a namespace collision (eg myapp_myvarname).

    run.py

    import __builtin__
    __builtin__.myapp_PATH_TO_R_SOURCE = 'path.to.r.source'
    import someClass
    

    someClass module .py

    import rpy2.robjects as robjects
    import __builtin__
    
    if hasattr(__builtin__, "myapp_PATH_TO_R_SOURCE"):
        PATH_TO_R_SOURCE = __builtin__.myapp_PATH_TO_R_SOURCE
    else:
        PATH_TO_R_SOURCE = ## Some default value or Null for Exception handling
    robjects.r.source(PATH_TO_R_SOURCE, chdir = True)
    
    ...
    

    This works well for variables that may have a default but you want to allow overriding at import time. If the __builtin__ variable is not set, it will use a default value.

    Edit: Some consider this an example of "Monkey patching". For a more elegant solution without monkey patch, see my other answer.

提交回复
热议问题