13
13
import typing as t
14
14
import warnings
15
15
16
+ from typing_extensions import Self
17
+
16
18
from libtmux ._internal .query_list import QueryList
17
19
from libtmux .common import has_gte_version , tmux_cmd
18
20
from libtmux .constants import (
28
30
from .common import PaneDict , WindowOptionDict , handle_option_error
29
31
30
32
if t .TYPE_CHECKING :
33
+ import types
34
+
31
35
from .server import Server
32
36
from .session import Session
33
37
@@ -73,6 +77,13 @@ class Window(Obj):
73
77
>>> window in session.windows
74
78
True
75
79
80
+ The window can be used as a context manager to ensure proper cleanup:
81
+
82
+ >>> with session.new_window() as window:
83
+ ... pane = window.split()
84
+ ... # Do work with the pane
85
+ ... # Window will be killed automatically when exiting the context
86
+
76
87
References
77
88
----------
78
89
.. [window_manual] tmux window. openbsd manpage for TMUX(1).
@@ -85,6 +96,39 @@ class Window(Obj):
85
96
86
97
server : Server
87
98
99
+ def __enter__ (self ) -> Self :
100
+ """Enter the context, returning self.
101
+
102
+ Returns
103
+ -------
104
+ :class:`Window`
105
+ The window instance
106
+ """
107
+ return self
108
+
109
+ def __exit__ (
110
+ self ,
111
+ exc_type : type [BaseException ] | None ,
112
+ exc_value : BaseException | None ,
113
+ exc_tb : types .TracebackType | None ,
114
+ ) -> None :
115
+ """Exit the context, killing the window if it exists.
116
+
117
+ Parameters
118
+ ----------
119
+ exc_type : type[BaseException] | None
120
+ The type of the exception that was raised
121
+ exc_value : BaseException | None
122
+ The instance of the exception that was raised
123
+ exc_tb : types.TracebackType | None
124
+ The traceback of the exception that was raised
125
+ """
126
+ if (
127
+ self .window_id is not None
128
+ and len (self .session .windows .filter (window_id = self .window_id )) > 0
129
+ ):
130
+ self .kill ()
131
+
88
132
def refresh (self ) -> None :
89
133
"""Refresh window attributes from tmux."""
90
134
assert isinstance (self .window_id , str )
0 commit comments