Use python decorator to automatically replace function argument parameter value?

Actually, the name does not accurately reflect the question I want to ask. My goal is this: I am writing some build functions using matplotlib. I have a number of functions that are designed for different purposes of graphing. for example line_plot () for strings, bar_plot () for a bar, etc., for example:

import matplotlib.pyplot as plt
def line_plot(axes=None,x=None,y=None):
    if axes==None:
        fig=plt.figure()
        axes=fig.add_subplot(111)
    else:
        pass
    axes.plot(x,y)

def bar_plot(axes=None,x=None,y=None):
    if axes==None:
        fig=plt.figure()
        axes=fig.add_subplot(111)
    else:
        pass
    axes.bar(left=x,height=y)

However, the problem is that for each specific function I have to repeat this part of the code:

    if axes==None:
        fig=plt.figure()
        axes=fig.add_subplot(111)
    else:
        pass

Is there a way, for example, using a decorator that I can apply before defining a graphing function that will automatically execute the repeating part of the code? Therefore, I should not repeat them every time.

one of the possible options is to define such a function:

def check_axes(axes):
    if axes==None:
        fig=plt.figure()
        axes=fig.add_subplot(111)
        return axes
    else:
        return axes

Then the examples will look like this:

import matplotlib.pyplot as plt    
def line_plot(axes=None,x=None,y=None):
    axes=check_axes(axes)
    axes.plot(x,y)

def bar_plot(axes=None,x=None,y=None):
    axes=check_axes(axes)
    axes.bar(left=x,height=y)

// ? , , . - ?

!!

+5
1

:

import matplotlib.pyplot as plt    

def check_axes(plot_fn):
    def _check_axes_wrapped_plot_fn(axes=None, x=None, y=None):
        if not axes:
            fig = plt.figure()
            axes = fig.add_subplot(111)
            return plot_fn(axes, x, y)
        else:
            return plot_fn(axes, x, y)
    return _check_axes_wrapped_plot_fn

@check_axes
def line_plot(axes, x=None, y=None):
    axes.plot(x, y)

@check_axes
def bar_plot(axes, x=None, y=None):
    axes.bar(left=x, height=y)

: @check_axes , . line_plot - , , .. _check_axes_wrapped_plot_fn. "" axes -checking, .

, check_axes , axes, , x y, Python handy * :

def check_axes(plot_fn):
    def _check_axes_wrapped_plot_fn(axes=None, *args):
        if not axes:
            fig = plt.figure()
            axes = fig.add_subplot(111)
            return plot_fn(axes, *args)  # pass all args after axes
        else:
            return plot_fn(axes, *args)  # pass all args after axes
    return _check_axes_wrapped_plot_fn  

, , "// Pythonic", , .

, " Pythonic" PEP8. , = ( , = ) not axes axes == None.

+7

All Articles