Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() like

def plot(
        self,
        show_this=True,
        show_that=True,
        color='k',
        boundary_color=None,
        other_color=[0.8, 0.8, 0.8],
        show_axes=True
        ):
    # lots of code
    return

def show(
        self,
        show_this=True,
        show_that=True,
        color='k',
        boundary_color=None,
        other_color=[0.8, 0.8, 0.8],
        show_axes=True
        ):
    from matplotlib import pyplot as plt
    self.plot(
        show_this=show_this,
        show_that=show_that,
        color=color,
        boundary_color=boundary_color,
        other_color=other_color,
        show_axes=show_axes
        )
    plt.show()
    return

This all works.

The issue I have is that this seems way too much code in the show() wrapper. What I really want: Let show() have the same signature and default arguments as plot(), and forward all arguments to it.

Any hints?

like image 542
Nico Schlömer Avatar asked May 08 '26 00:05

Nico Schlömer


1 Answers

Python 3 offers the ability to actually copy the signature of the wrapped function with the inspect module:

def show(self, *args, **kwargs):
    from matplotlib import pyplot as plt
    self.plot(*args, **kwargs)
    plt.show()
show.__signature__ = inspect.signature(plot)

Now if you use show in a shell that provides autocompletion like IDLE, you will see the correct parameters for show instead of the cryptics *args, **kwargs

like image 108
Serge Ballesta Avatar answered May 09 '26 13:05

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!