1

Currently I have a module that when It is imported a for loop is executed:

numbers.py

DICT_NUMBER = {
    'one': One,
    'two': Two,
    'three': Three,
    'four': Four,
    'five': Five,
}

for num in DICT_NUMBER.values():
    if not issubclass(num, Number):
        raise Exception(f'{num} is not extending Number')

The problem is that I don't know how to test it, I've tried to do the following code:

from numbers.py import DICT_NUMBER # the for is executed without raise Exception

DICT_NUMBER['A'] = A # 'A' don't extends Number

with self.assertRaises(Exception):
   from numbers.py import DICT_NUMBER

This does not work because DICT_NUMBER turns into a unresolved reference.

There is any way to do it?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    it's probably better to use a type checker to enforce this rather than a test -- `DICT_NUMBER: dict[str, type[Number]] = { ... }` – anthony sottile Nov 17 '21 at 18:53

1 Answers1

2

You cannot double import a module, only reload it as specified here: how to reload a python module. In your case module file is not changing so reload will not help. Try to move the for part into a function with a dict parameter and then test it with different inputs.

Dan Constantinescu
  • 1,426
  • 1
  • 7
  • 11