use python decorator to automatically replace function argument default value?

Viewed 12795

Actually the title does not reflect exactly the question I want to ask. My purpose is like this: I am writing some plotting functions by using matplotlib. I have a series of functions that are for different plotting purpose. like line_plot() for lines, bar_plot() for 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)

Yet the problem is, for each function that's defined, I have to repeat this part of code:

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

Is there way like by using a decorator, which I can apply before the definition of the plotting function, that will do the repeated part of code automatically? Thus I don't have to repeat them each time.

one possible option is to define a function like this:

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

Then the examples will be like:

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)

But Is there a better/clean/more pythonic way? I guess I can use a decorator but didn't figure it out. could anybody give some idea?

Thanks!!

1 Answers
Related