Guido van Rossum | ad50ca9 | 2002-12-30 22:30:22 +0000 | [diff] [blame] | 1 | """Faux ``threading`` version using ``dummy_thread`` instead of ``thread``. |
| 2 | |
| 3 | The module ``_dummy_threading`` is added to ``sys.modules`` in order |
| 4 | to not have ``threading`` considered imported. Had ``threading`` been |
| 5 | directly imported it would have made all subsequent imports succeed |
| 6 | regardless of whether ``thread`` was available which is not desired. |
| 7 | |
| 8 | :Author: Brett Cannon |
| 9 | :Contact: brett@python.org |
| 10 | |
| 11 | XXX: Try to get rid of ``_dummy_threading``. |
| 12 | |
| 13 | """ |
| 14 | from sys import modules as sys_modules |
| 15 | |
| 16 | import dummy_thread |
| 17 | |
| 18 | # Declaring now so as to not have to nest ``try``s to get proper clean-up. |
| 19 | holding_thread = False |
| 20 | holding_threading = False |
| 21 | |
| 22 | try: |
| 23 | # Could have checked if ``thread`` was not in sys.modules and gone |
| 24 | # a different route, but decided to mirror technique used with |
| 25 | # ``threading`` below. |
| 26 | if 'thread' in sys_modules: |
| 27 | held_thread = sys_modules['thread'] |
| 28 | holding_thread = True |
| 29 | # Must have some module named ``thread`` that implements its API |
| 30 | # in order to initially import ``threading``. |
| 31 | sys_modules['thread'] = sys_modules['dummy_thread'] |
| 32 | |
| 33 | if 'threading' in sys_modules: |
| 34 | # If ``threading`` is already imported, might as well prevent |
| 35 | # trying to import it more than needed by saving it if it is |
| 36 | # already imported before deleting it. |
| 37 | held_threading = sys_modules['threading'] |
| 38 | holding_threading = True |
| 39 | del sys_modules['threading'] |
| 40 | import threading |
| 41 | # Need a copy of the code kept somewhere... |
| 42 | sys_modules['_dummy_threading'] = sys_modules['threading'] |
| 43 | del sys_modules['threading'] |
| 44 | from _dummy_threading import * |
| 45 | from _dummy_threading import __all__ |
| 46 | |
| 47 | finally: |
| 48 | # Put back ``threading`` if we overwrote earlier |
| 49 | if holding_threading: |
| 50 | sys_modules['threading'] = held_threading |
| 51 | del held_threading |
| 52 | del holding_threading |
| 53 | |
| 54 | # Put back ``thread`` if we overwrote, else del the entry we made |
| 55 | if holding_thread: |
| 56 | sys_modules['thread'] = held_thread |
| 57 | del held_thread |
| 58 | else: |
| 59 | del sys_modules['thread'] |
| 60 | del holding_thread |
| 61 | |
| 62 | del dummy_thread |
| 63 | del sys_modules |