SF #1499797, Fix for memory leak in WindowsError_str
[python.git] / Lib / dummy_threading.py
blob48f7c4c74699e52798b1a500741d11ab3179ef1d
1 """Faux ``threading`` version using ``dummy_thread`` instead of ``thread``.
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.
8 :Author: Brett Cannon
9 :Contact: brett@python.org
11 XXX: Try to get rid of ``_dummy_threading``.
13 """
14 from sys import modules as sys_modules
16 import dummy_thread
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 holding__threading_local = False
23 try:
24 # Could have checked if ``thread`` was not in sys.modules and gone
25 # a different route, but decided to mirror technique used with
26 # ``threading`` below.
27 if 'thread' in sys_modules:
28 held_thread = sys_modules['thread']
29 holding_thread = True
30 # Must have some module named ``thread`` that implements its API
31 # in order to initially import ``threading``.
32 sys_modules['thread'] = sys_modules['dummy_thread']
34 if 'threading' in sys_modules:
35 # If ``threading`` is already imported, might as well prevent
36 # trying to import it more than needed by saving it if it is
37 # already imported before deleting it.
38 held_threading = sys_modules['threading']
39 holding_threading = True
40 del sys_modules['threading']
42 if '_threading_local' in sys_modules:
43 # If ``_threading_local`` is already imported, might as well prevent
44 # trying to import it more than needed by saving it if it is
45 # already imported before deleting it.
46 held__threading_local = sys_modules['_threading_local']
47 holding__threading_local = True
48 del sys_modules['_threading_local']
50 import threading
51 # Need a copy of the code kept somewhere...
52 sys_modules['_dummy_threading'] = sys_modules['threading']
53 del sys_modules['threading']
54 sys_modules['_dummy__threading_local'] = sys_modules['_threading_local']
55 del sys_modules['_threading_local']
56 from _dummy_threading import *
57 from _dummy_threading import __all__
59 finally:
60 # Put back ``threading`` if we overwrote earlier
62 if holding_threading:
63 sys_modules['threading'] = held_threading
64 del held_threading
65 del holding_threading
67 # Put back ``_threading_local`` if we overwrote earlier
69 if holding__threading_local:
70 sys_modules['_threading_local'] = held__threading_local
71 del held__threading_local
72 del holding__threading_local
74 # Put back ``thread`` if we overwrote, else del the entry we made
75 if holding_thread:
76 sys_modules['thread'] = held_thread
77 del held_thread
78 else:
79 del sys_modules['thread']
80 del holding_thread
82 del dummy_thread
83 del sys_modules