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
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.
One particular module deserves some attention: sys, which is built into every Python interpreter.
The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With