Modules and imports · 14 / 16 Exercise Medium

Importing only once

Objective

Python stores the modules that have already been imported in the sys.modules dictionary: if you import one again, it is not run again, it is reused. Reproduce that mechanism with your own dictionary loaded.

Instructions

  • Use the SOURCES dictionary from the statement in your code: "alfa": ... , "beta": ... is the code of each module, and both show Loading name when run and define VALOR.
  • Create an empty dictionary loaded and write import_module_once(name): if the module is already in loaded, return it; otherwise create a module with types.ModuleType(name), store it in loaded and run its code with exec(code, module.__dict__).
  • Read n and then n module names. If it is not in SOURCES, show Unknown module: name.
  • Otherwise import the module and show name.VALOR = value.
Input
4
alfa
beta
alfa
alfa
Output
Loading alfa
alfa.VALOR = 10
Loading beta
beta.VALOR = 20
alfa.VALOR = 10
alfa.VALOR = 10

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise