'How to avoid RuntimeError while call __dict__ on module?

it is appearing in some big modules like matplotlib. For example expression :

import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__ 

Between runs len of obj_entries can vary. From 108 to 157 (expected) entries. Especially pyplot can be ignored like some another submodules. it can work stable during manual debug mode with len computing statement after dict extraction. But in auto it dont work well.

such error occures:

RuntimeError: dictionary changed size during iteration
python-BaseException

using clear python 3.10 on windows. Version swap change nothing at all



Solution 1:[1]

during some attempts some interesting features was found. use of repr is helpfull before dict initiation. But if module transported between classes like variable more likely lazy-import happening? For now there is evidence that not all names showing when command line interpriter doing opposite - returning what expected. So this junk of code help bypass this bechavior... Note: using pkgutil.iter_modules(some_path) to observe modules im internal for pkgutil ModuleInfo form.

import pkgutil, importlib

module_info : pkgutil.ModuleInfo
name = module_info.name
founder = module_info.module_finder
spec = founder.find_spec(name)
module_obj = importlib.util.module_from_spec(spec)
loader = module_obj.__loader__
loader.exec_module(module_obj)

still unfamilliar with interior of import mechanics so it will be helpfull to recive some links to more detail explanation (spot on)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xillmera