Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating module in sys.modules causes sys to become None

Tags:

python

I'm creating a module called Qt (Github link) where I alias another module (for example PyQt4), so that when I import Qt I am in fact importing PyQt4:

from Qt import QtWidgets  # this really imports PyQt4.QtGui

Example Qt module:

# Qt.py
import sys
import PyQt4.Qt

sys.modules["Qt"] = PyQt4
PyQt4.QtWidgets = PyQt4.QtGui

However, If I add print sys at the end of Qt.py, sys equals None:

print sys
>>> None

Why does sys "break" and can I avoid breaking it?

This is in Python 2.7.11 on OS X.


@Lol4t0 – Here's an example where I'm only using standard modules:

# Xyz.py

import os
import sys

sys.modules['Xyz'] = os
print sys  # this will print "None"

So importing this will result in that "None is printed:

$ python
Python 2.7.11 (default, Jan 22 2016, 08:29:18)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Xyz
None
like image 669
fredrik Avatar asked May 28 '16 12:05

fredrik


People also ask

What does sys module do?

The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter.

Is sys a Python built in module?

One particular module deserves some attention: sys, which is built into every Python interpreter.

What does Importlib Import_module do?

The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib.

What happens when you import a module Python?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


1 Answers

When there are no longer any reference to a module, it will drop all its globals by replacing them with None.

You need to remember the old verion of sys.modules['Xyz'] (i.e. the current module) until you are done executing it.

like image 126
o11c Avatar answered Oct 04 '22 03:10

o11c