PyREx

pyrex.internal_functions.mirror_func

pyrex.internal_functions.mirror_func(match_func, run_func, self=None)

Mirror the attributes of one function onto another.

Creates a function which operates like one function, but has all the attributes of another. Works for functions or class methods.

Parameters
match_funcfunction

Function with the attributes to be mirrored.

run_funcfunction

Function with the desired behavior.

selfobject or None, optional

If None, run_func called as a regular function, otherwise run_func is called as a class method (with self as its first argument).

Returns
function

Function with the behavior of run_func, but the attributes of match_func.

Examples

>>> from inspect import signature
>>> def descriptive_add(a, b):
...     """Function with a descriptive docstring."""
...     pass
>>> def add_implementation(x, y):
...     # Actually adds, but no docs or anything
...     return x+y
>>> my_add = mirror_func(descriptive_add, add_implementation)
>>> my_add(2, 3)
5
>>> my_add.__doc__
'Function with a descriptive docstring.'
>>> signature(my_add)
<Signature (a, b)>
>>> from inspect import signature
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def mult(self, factor, power=1):
...         """Multiplies value by factor and raises to power."""
...         return (self.value*factor)**power
>>> class B(A):
...     def __init__(self, value):
...         self.value = value
...         # Make the mult method look the same as for A, but with
...         # different behavior
...         self.mult = mirror_func(A.mult, B.different_mult, self=self)
...     def different_mult(self, *args, **kwargs):
...         """Different implementation of mult."""
...         return (self.value*int(args[0]))**kwargs['power']
>>> b = B(5)
>>> b.mult(2.5, power=2)
100
>>> b.mult.__doc__
'Multiplies by factor and raises to power.'
>>> signature(b.mult)
<Signature (self, factor, power=1)>

PyREx

A Python package for simulation of neutrinos and radio antennas in ice. Version 1.10.0

Navigation