How can I override a constant in an imported Python module?

后端 未结 4 787
再見小時候
再見小時候 2020-12-17 10:33

In my application I am using module within the package example called examplemod.

My app:

from example imp         


        
相关标签:
4条回答
  • 2020-12-17 10:51

    I'm not sure if this is enough or not, but did you try:

    from example import config
    config.CONSTANT = "A desirable value"
    

    Make sure to do this before examplemod is imported. This should work because python caches imports so the config that you modified will be the same one that examplemod gets.

    0 讨论(0)
  • 2020-12-17 10:57

    Yes, but it'll only work as expected with fully qualified access paths to modules:

    import example
    example.examplemod.config.CONSTANT = "Better value"
    example.examplemod.do_stuff()
    
    0 讨论(0)
  • 2020-12-17 10:57

    This is called monkey patching, and it's fairly common although not preferred if there's another way to accomplish the same thing:

    examplemod.config.CONSTANT = "Better value"
    

    The issue is that you're relying on the internals of examplemod and config remaining the same, so this could break if either module changes.

    0 讨论(0)
  • 2020-12-17 11:08

    Thank you all for your answers. They pointed me in the right direction though none of them worked as written. I ended up doing the following:

    import example.config
    example.config.CONSTANT = "Better value"
    
    from example import examplemod
    examplemod.do_stuff()
    # desired result!
    

    (Also, I'm submitting a patch to the module maintainer to make CONSTANT a configurable option so I don't have to do this but need to install the stock module in the mean time.)

    0 讨论(0)
提交回复
热议问题