Debian Codegraph @

gavo/utils/monkeypatch.py

raw
1 """
2 This module contains monkey patches for the python standard library
3 where we want to use features beyond the current base line (python 3.7).
4
5 It is imported early on by utils.__init__, so anything that is in DaCHS
6 should be able to rely on these patches.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import functools
16 import threading
17
18 if not hasattr(functools, "cached_property"): # pragma: no cover
19 functools._NOT_FOUND = object()
20
21 class cached_property:
22 def __init__(self, func):
23 self.func = func
24 self.attrname = None
25 self.__doc__ = func.__doc__
26 self.lock = threading.RLock()
27
28 def __set_name__(self, owner, name):
29 if self.attrname is None:
30 self.attrname = name
31 elif name != self.attrname:
32 raise TypeError(
33 "Cannot assign the same cached_property to two different names "
34 f"({self.attrname!r} and {name!r})."
35 )
36
37 def __get__(self, instance, owner=None):
38 if instance is None:
39 return self
40 if self.attrname is None:
41 raise TypeError(
42 "Cannot use cached_property instance without calling __set_name__ on it.")
43 try:
44 cache = instance.__dict__
45 except AttributeError: # not all objects have __dict__ (e.g. class defines slots)
46 msg = (
47 f"No '__dict__' attribute on {type(instance).__name__!r} "
48 f"instance to cache {self.attrname!r} property."
49 )
50 raise TypeError(msg) from None
51 val = cache.get(self.attrname, functools._NOT_FOUND)
52 if val is functools._NOT_FOUND:
53 with self.lock:
54 # check if another thread filled cache while we awaited lock
55 val = cache.get(self.attrname, functools._NOT_FOUND)
56 if val is functools._NOT_FOUND:
57 val = self.func(instance)
58 try:
59 cache[self.attrname] = val
60 except TypeError:
61 msg = (
62 f"The '__dict__' attribute on {type(instance).__name__!r} instance "
63 f"does not support item assignment for caching {self.attrname!r} property."
64 )
65 raise TypeError(msg) from None
66 return val
67
68 functools.cached_property = cached_property
69
70
71 # Work around a rather severe openssl bug leading to presumably
72 # exploitable crashes https://twistedmatrix.com/trac/ticket/9764
73 from OpenSSL import SSL
74
75 def patch_openssl():
76 original = SSL.Context.__init__
77
78 def newInit(self, method):
79 original(self, method)
80 self.set_session_cache_mode(SSL.SESS_CACHE_OFF)
81
82 SSL.Context.__init__ = newInit
83
84 patch_openssl()