It would be safer / simpler just to convert to a list unconditionally, e.g.::

    for module in list(sys.modules.values()):
        ...