|
| 1 | +# Copyright 2018 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import functools |
| 16 | + |
| 17 | + |
| 18 | +def dispatch(func): |
| 19 | + """Return a decorated method that dispatches on the second argument. |
| 20 | +
|
| 21 | + This is the equivalent of :meth:`functools.singledispatch`, but for |
| 22 | + bound methods. |
| 23 | + """ |
| 24 | + base_dispatcher = functools.singledispatch(func) |
| 25 | + |
| 26 | + # Define a wrapper function that works off args[1] instead of args[0]. |
| 27 | + # This is needed because we are overloading *methods*, and their first |
| 28 | + # argument is always `self`. |
| 29 | + @functools.wraps(base_dispatcher) |
| 30 | + def wrapper(*args, **kwargs): |
| 31 | + return base_dispatcher.dispatch(args[1].__class__)(*args, **kwargs) |
| 32 | + |
| 33 | + # The register function is not changed, so let singledispatch do the work. |
| 34 | + wrapper.register = base_dispatcher.register |
| 35 | + |
| 36 | + # Done; return the decorated method. |
| 37 | + return wrapper |
0 commit comments