31

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

My app:

from example import examplemod
examplemod.do_stuff()

It imports another module within example like so.

examplemod.py:

from example import config
# uses config
# then does stuff

config uses a constant.

config.py:

CONSTANT = "Unfortunate value"

I'd like to override this constant when I'm using examplemod in my application (setting it to CONSTANT = "Better value") and I'd prefer not to modify the underlying module so I don't have to maintain my own package. How can I do this?

Dave Forgac
  • 3,146
  • 7
  • 39
  • 54

4 Answers4

31

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()
vartec
  • 131,205
  • 36
  • 218
  • 244
  • 1
    Also worth mentioning that if the examplemod module imported CONSTANT directly into its symbol table with the `from config import CONSTANT` syntax, you'd need to do `example.examplemod.CONSTANT = "Better value"`, since examplemod would then have its own reference to CONSTANT. The form that you're using replaces config.CONSTANT, which works in the case that the examplemod module is using `from examplemod import config; config.CONSTANT`. – Symmetric Oct 07 '14 at 17:08
17

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.)

Dave Forgac
  • 3,146
  • 7
  • 39
  • 54
3

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.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

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.

ubershmekel
  • 11,864
  • 10
  • 72
  • 89