0

Background to avoid the XY problem

I use unittest and run tests via discovery. I want the various tests to be able to read some variable GLOB that is set at runtime, which creates some circular imports. Say runner.py is the script that runs the tests and test_a.py one of the test files to be run, then:

  • runner.py must import test_a.py (during discovery) to run the tests
  • test_a.py must read GLOB which either lives in runner.py or in something that calls it

I think the unittest boilerplate is irrelevant to the problem (see examples below which do not involve it) but a solution specific to that problem would work for me.

I tagged "global-variables" but this might not be the good terminology (somemodule.somevariable would work fine if it was not for the circular import tricks).

Question and demo files

If module a imports module b, how can module b read a value from module a that can change after b imports a?

a.py:

import b
GLOB = 0

def get_glob():
    '''an attempt to ensure a call at runtime, but does not solve the problem'''
    return GLOB

def printy():
    print('Value in a:', GLOB, get_glob())

if __name__ == '__main__':
    GLOB = 1
    printy()  # 1, 1
    b.printy()  # 0, 0 not 1, 1

b.py:

import a

def printy():
    print('Value in b:', a.GLOB, a.get_glob())

Reading around (e.g. Circular (or cyclic) imports in Python) I see mostly "avoid circular imports" but (cf. background) it cannot be avoided here. In my case I could read/write from disk (no multithreading or performance bottleneck) but that seems really awful.

Leporello
  • 638
  • 4
  • 12

0 Answers0