Pass Variable On Import

后端 未结 8 1375
轻奢々
轻奢々 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:18

    There is no way to pass a variable at import.

    Some ideas:

    • make the module get the variable from the calling module using inspection; not very pythonic
    • use an Init function for the module, this is the best way
    0 讨论(0)
  • 2020-12-16 10:19

    Couple of other options that can achieve your goal (although a init() function is probably cleaner):

    • Use an environment variable
    • Use a separate module M to hold this variable, that the importer would set. Then the imported module could either know where to find M, or could rely on sys.meta_path to obtain it.
    0 讨论(0)
提交回复
热议问题