|
100 | 100 | ]
|
101 | 101 |
|
102 | 102 |
|
103 |
| -class InstanceMethod: |
104 |
| - """Class for hiding references to instance methods so they can be pickled. |
105 |
| -
|
106 |
| - >>> self.method = InstanceMethod(some_object, 'method_name') |
107 |
| - """ |
108 |
| - |
109 |
| - def __init__(self, obj, method_name): |
110 |
| - self.obj = obj |
111 |
| - self.method_name = method_name |
112 |
| - |
113 |
| - def __call__(self, *args, **kwargs): |
114 |
| - return getattr(self.obj, self.method_name)(*args, **kwargs) |
115 |
| - |
116 |
| - |
117 |
| -def incorporate_methods(source, destination, methods, wrapper=None, override=False): |
118 |
| - """ |
119 |
| - Add attributes to a destination object which point to |
120 |
| - methods from from a source object. |
121 |
| -
|
122 |
| - Parameters |
123 |
| - ---------- |
124 |
| - source: object |
125 |
| - The source object containing the methods. |
126 |
| - destination: object |
127 |
| - The destination object for the methods. |
128 |
| - methods: list of str |
129 |
| - Names of methods to incorporate. |
130 |
| - wrapper: function |
131 |
| - An optional function to allow the source method to be |
132 |
| - wrapped. Should take the form my_wrapper(source, method_name) |
133 |
| - and return a single value. |
134 |
| - override: bool |
135 |
| - If the destination object already has a method/attribute |
136 |
| - an AttributeError will be raised if override is False (the default). |
137 |
| - """ |
138 |
| - for method in methods: |
139 |
| - if hasattr(destination, method) and not override: |
140 |
| - raise AttributeError( |
141 |
| - f"Cannot add method {method!r}" + "to destination object as it already exists. " |
142 |
| - "To prevent this error set 'override=True'." |
143 |
| - ) |
144 |
| - if hasattr(source, method): |
145 |
| - if wrapper is None: |
146 |
| - setattr(destination, method, getattr(source, method)) |
147 |
| - else: |
148 |
| - setattr(destination, method, wrapper(source, method)) |
149 |
| - else: |
150 |
| - setattr(destination, method, None) |
151 |
| - |
152 |
| - |
153 | 103 | T = TypeVar("T", bound="ContextMeta")
|
154 | 104 |
|
155 | 105 |
|
|
0 commit comments