1313import typing as t
1414import warnings
1515
16+ from typing_extensions import Self
17+
1618from libtmux ._internal .query_list import QueryList
1719from libtmux .common import has_gte_version , tmux_cmd
1820from libtmux .constants import (
2830from .common import PaneDict , WindowOptionDict , handle_option_error
2931
3032if t .TYPE_CHECKING :
33+ import types
34+
3135 from .server import Server
3236 from .session import Session
3337
@@ -73,6 +77,13 @@ class Window(Obj):
7377 >>> window in session.windows
7478 True
7579
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+
7687 References
7788 ----------
7889 .. [window_manual] tmux window. openbsd manpage for TMUX(1).
@@ -85,6 +96,39 @@ class Window(Obj):
8596
8697 server : Server
8798
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+
88132 def refresh (self ) -> None :
89133 """Refresh window attributes from tmux."""
90134 assert isinstance (self .window_id , str )
0 commit comments