Temporarily set some attributes; restore original state at context exit.
(obj, **kwargs)
| 2134 | |
| 2135 | @contextlib.contextmanager |
| 2136 | def _setattr_cm(obj, **kwargs): |
| 2137 | """ |
| 2138 | Temporarily set some attributes; restore original state at context exit. |
| 2139 | """ |
| 2140 | sentinel = object() |
| 2141 | origs = {} |
| 2142 | for attr in kwargs: |
| 2143 | orig = getattr(obj, attr, sentinel) |
| 2144 | if attr in obj.__dict__ or orig is sentinel: |
| 2145 | # if we are pulling from the instance dict or the object |
| 2146 | # does not have this attribute we can trust the above |
| 2147 | origs[attr] = orig |
| 2148 | else: |
| 2149 | # if the attribute is not in the instance dict it must be |
| 2150 | # from the class level |
| 2151 | cls_orig = getattr(type(obj), attr) |
| 2152 | # if we are dealing with a property (but not a general descriptor) |
| 2153 | # we want to set the original value back. |
| 2154 | if isinstance(cls_orig, property): |
| 2155 | origs[attr] = orig |
| 2156 | # otherwise this is _something_ we are going to shadow at |
| 2157 | # the instance dict level from higher up in the MRO. We |
| 2158 | # are going to assume we can delattr(obj, attr) to clean |
| 2159 | # up after ourselves. It is possible that this code will |
| 2160 | # fail if used with a non-property custom descriptor which |
| 2161 | # implements __set__ (and __delete__ does not act like a |
| 2162 | # stack). However, this is an internal tool and we do not |
| 2163 | # currently have any custom descriptors. |
| 2164 | else: |
| 2165 | origs[attr] = sentinel |
| 2166 | |
| 2167 | try: |
| 2168 | for attr, val in kwargs.items(): |
| 2169 | setattr(obj, attr, val) |
| 2170 | yield |
| 2171 | finally: |
| 2172 | for attr, orig in origs.items(): |
| 2173 | if orig is sentinel: |
| 2174 | delattr(obj, attr) |
| 2175 | else: |
| 2176 | setattr(obj, attr, orig) |
| 2177 | |
| 2178 | |
| 2179 | class _OrderedSet(collections.abc.MutableSet): |
no outgoing calls
no test coverage detected
searching dependent graphs…