Skip to content

Commit c9a9235

Browse files
committed
Made ContextFlag reentrant
1 parent 93506e8 commit c9a9235

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

cmd2/utils.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,6 @@ def which(editor: str) -> Optional[str]:
142142
:param editor: filename of the editor to check, ie 'notepad.exe' or 'vi'
143143
:return: a full path or None
144144
"""
145-
import subprocess
146145
try:
147146
editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()
148147
editor_path = editor_path.decode()
@@ -476,19 +475,23 @@ def _write_bytes(stream: Union[StdSim, BinaryIO, TextIO], to_write: bytes) -> No
476475

477476
class ContextFlag(object):
478477
"""
479-
A flag value that can be used in a with statement.
478+
A flag value that is used in a with statement.
480479
Its main use is as a flag to prevent the SIGINT handler in cmd2 from raising a KeyboardInterrupt
481-
while another code section has set the flag to True. Because signal handling is always done on the
482-
main thread, this class is not thread since there is no need.
480+
while a critical code section has set the flag to True. Because signal handling is always done on the
481+
main thread, this class is not thread-safe since there is no need.
483482
"""
484-
def __init__(self, value):
485-
self.value = value
483+
def __init__(self):
484+
# When this flag has a positive value, it is considered set.
485+
# When it is 0, it is not set. It should never go below 0.
486+
self.__count = 0
486487

487488
def __bool__(self):
488-
return self.value
489+
return self.__count > 0
489490

490491
def __enter__(self):
491-
self.value = True
492+
self.__count += 1
492493

493494
def __exit__(self, *args):
494-
self.value = False
495+
self.__count -= 1
496+
if self.__count < 0:
497+
raise ValueError("count has gone below 0")

0 commit comments

Comments
 (0)