1

I am trying to add a module-level attribute to config file and want to do something like this..

# repo/__init__.py file
pass

# repo/config.py file
VERIFY_CERTS = True

and then, use this variable in other sub-modules

# repo/example.py
from repo.config import VERIFY_CERTS
def do_something():
    if VERIFY_CERTS:
        do something..
    else:
        do something else

Now, when I use this repo module in another script, I want to be able to do:

from repo.config import VERIFY_CERTS
VERIFY_CERTS = False
from repo.example import do_something
do_something()

Is it possible to do something like this?

Edit: It is definitely not a duplicate of Immutable vs Mutable types since, it discusses something about mutable and immutable datatypes whereas, this one is about having a module level attribute that could be remembered in a session. Modified variable names to clarify why I want to do this.

manji369
  • 186
  • 4
  • 16
  • I know what you want to do, but I don't see the application of it. Like why do you need to `import X` at all, and why do you need to have an import that's not at the top of the file? – wjandrea Feb 13 '19 at 23:18
  • Possible duplicate of [Immutable vs Mutable types](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types) – Stephen Rauch Feb 13 '19 at 23:51
  • @wjandrea renamed variables to make it more clear – manji369 Feb 14 '19 at 17:45

1 Answers1

0

Problem

From what I understand, you want to change the value of VERIFY_CERTS that do_something() uses.

Firstly, your example can be simplified like this:

example.py

VERIFY_CERTS = True
def do_something():
    print(VERIFY_CERTS)

test.py

from example import do_something
VERIFY_CERTS = False
do_something()

Running test.py will print True.


Solution

In test.py, simply import the whole module example (this is best practice for imports anyway), then set example.VERIFY_CERTS.

import example
example.VERIFY_CERTS = False
example.do_something()

Running this will print False.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Thanks for the response. But, this is just a small part of a big project and so I can't simplify it to move the config out. I got around this by using a different approach of using class variables instead. – manji369 Feb 21 '19 at 21:15
  • @manji369 Oh, I assumed `repo` was a third-party module you didn't have control over, and you were just writing a script that uses it. – wjandrea Feb 22 '19 at 15:00