File tree 2 files changed +54
-16
lines changed
2 files changed +54
-16
lines changed Original file line number Diff line number Diff line change 1
1
import nose
2
2
3
- from contextlib import contextmanager
4
3
import os
5
4
import datetime
6
5
import numpy as np
16
15
import pandas .util .testing as tm
17
16
from pandas .util .testing import (ensure_clean , assert_index_equal ,
18
17
assert_series_equal ,
19
- assert_frame_equal )
18
+ assert_frame_equal ,
19
+ patch )
20
20
from pandas .tests .test_panel import assert_panel_equal
21
21
22
22
import pandas
@@ -59,20 +59,6 @@ def check_arbitrary(a, b):
59
59
assert (a == b )
60
60
61
61
62
- @contextmanager
63
- def patch (ob , attr , value ):
64
- noattr = object () # mark that the attribute never existed
65
- old = getattr (ob , attr , noattr )
66
- setattr (ob , attr , value )
67
- try :
68
- yield
69
- finally :
70
- if old is noattr :
71
- delattr (ob , attr )
72
- else :
73
- setattr (ob , attr , old )
74
-
75
-
76
62
class TestPackers (tm .TestCase ):
77
63
78
64
def setUp (self ):
Original file line number Diff line number Diff line change @@ -2243,3 +2243,55 @@ class SubclassedDataFrame(DataFrame):
2243
2243
@property
2244
2244
def _constructor (self ):
2245
2245
return SubclassedDataFrame
2246
+
2247
+
2248
+ @contextmanager
2249
+ def patch (ob , attr , value ):
2250
+ """Temporarily patch an attribute of an object.
2251
+
2252
+ Parameters
2253
+ ----------
2254
+ ob : any
2255
+ The object to patch. This must support attribute assignment for `attr`.
2256
+ attr : str
2257
+ The name of the attribute to patch.
2258
+ value : any
2259
+ The temporary attribute to assign.
2260
+
2261
+ Examples
2262
+ --------
2263
+ >>> class C(object):
2264
+ ... attribute = 'original'
2265
+ ...
2266
+ >>> C.attribute
2267
+ 'original'
2268
+ >>> with patch(C, 'attribute', 'patched'):
2269
+ ... in_context = C.attribute
2270
+ ...
2271
+ >>> in_context
2272
+ 'patched'
2273
+ >>> C.attribute # the value is reset when the context manager exists
2274
+ 'original'
2275
+
2276
+ Correctly replaces attribute when the manager exits with an exception.
2277
+ >>> with patch(C, 'attribute', 'patched'):
2278
+ ... in_context = C.attribute
2279
+ ... raise ValueError()
2280
+ Traceback (most recent call last):
2281
+ ...
2282
+ ValueError
2283
+ >>> in_context
2284
+ 'patched'
2285
+ >>> C.attribute
2286
+ 'original'
2287
+ """
2288
+ noattr = object () # mark that the attribute never existed
2289
+ old = getattr (ob , attr , noattr )
2290
+ setattr (ob , attr , value )
2291
+ try :
2292
+ yield
2293
+ finally :
2294
+ if old is noattr :
2295
+ delattr (ob , attr )
2296
+ else :
2297
+ setattr (ob , attr , old )
You can’t perform that action at this time.
0 commit comments