Gentoo Archives: gentoo-portage-dev

From: Florian Schmaus <flo@×××××××××.eu>
To: gentoo-portage-dev@l.g.o
Cc: Florian Schmaus <flo@×××××××××.eu>
Subject: [gentoo-portage-dev] [PATCH 1/2] Make atomic_ofstream a Context Manager
Date: Fri, 18 Dec 2020 18:46:58
Message-Id: 20201218184639.361607-1-flo@geekplace.eu
1 This allows using a "with statement" together with instances of
2 atomic_ofstream. Allowing for more readable, less error prone and
3 shorter code.
4
5 Signed-off-by: Florian Schmaus <flo@×××××××××.eu>
6 ---
7 lib/portage/util/__init__.py | 10 +++++++++-
8 1 file changed, 9 insertions(+), 1 deletion(-)
9
10 diff --git a/lib/portage/util/__init__.py b/lib/portage/util/__init__.py
11 index 0412b2b5911f..bedcbcfe6fcc 100644
12 --- a/lib/portage/util/__init__.py
13 +++ b/lib/portage/util/__init__.py
14 @@ -11,6 +11,7 @@ __all__ = ['apply_permissions', 'apply_recursive_permissions',
15 'stack_dicts', 'stack_lists', 'unique_array', 'unique_everseen', 'varexpand',
16 'write_atomic', 'writedict', 'writemsg', 'writemsg_level', 'writemsg_stdout']
17
18 +from contextlib import AbstractContextManager
19 from copy import deepcopy
20 import errno
21 import io
22 @@ -1246,7 +1247,7 @@ def apply_secpass_permissions(filename, uid=-1, gid=-1, mode=-1, mask=-1,
23 stat_cached=stat_cached, follow_links=follow_links)
24 return all_applied
25
26 -class atomic_ofstream(ObjectProxy):
27 +class atomic_ofstream(AbstractContextManager, ObjectProxy):
28 """Write a file atomically via os.rename(). Atomic replacement prevents
29 interprocess interference and prevents corruption of the target
30 file when the write is interrupted (for example, when an 'out of space'
31 @@ -1287,6 +1288,13 @@ class atomic_ofstream(ObjectProxy):
32 encoding=_encodings['fs'], errors='strict'),
33 mode=mode, **kargs))
34
35 + def __exit__(self, exc_type, exc_val, exc_tb):
36 + if exc_type is not None:
37 + self.abort()
38 + else:
39 + self.close()
40 + return None
41 +
42 def _get_target(self):
43 return object.__getattribute__(self, '_file')
44
45 --
46 2.26.2

Replies