elfe
elfe

Reputation: 79

how to create a function with optional parameter python3

I have a plotting function to plot some data. I would like to syntax it in a way that it will automatically get y limits,EXCEPT when I manually want to pass specific limits to it.

I have done that by manually changing the value in a variable,when i want my own axis limits to be used. However I understand that this is just a work around, so any suggestions are welcome:

def plot_data(dataset, set_own_lim=1, my_ymin, my_ymax):
       ax=plt.subplot(111)
             if set_own_lim=0:
                ax.set_ylim(min(dataset),max(dataset)) #calculating y range from data
             else:
                ax.set_ylim(my_ymin, my_ymax)        # uses my own limits for y range
       ax.plot(dataset)

I would like to define a function in a way, that I could call it like plot_data(some_data) to get automatic limits from data and I could also call it as plot_data(some_data,my_ymin, my_ymax), when i need to define the axis range manually

Upvotes: 1

Views: 170

Answers (2)

Brad Solomon
Brad Solomon

Reputation: 40878

Simpler use of None:

def plot_data(dataset, ymin=None, ymax=None):
   # ...
   ymin = min(dataset) if ymin is None else ymin
   ymax = max(dataset) if ymax is None else ymax
   # ...

Keep in mind however, that this would disable you from actually passing None to set_XXXlim(). In that case, you can use a sentinel value:

sentinel = object()

def plot_data(dataset, ymin=sentinel, ymax=sentinel):
   # ...
   ymin = min(dataset) if ymin is sentinel else ymin
   ymax = max(dataset) if ymax is sentinel else ymax
   # ...

which will permit plot_data(data, None, None).

Upvotes: 1

techytushar
techytushar

Reputation: 803

Set the my_ymin, my_ymax arguments are None and inside the function you can put a check if these values are None then you can calculate them otherwise use the values passed by the user. Like so:

def plot_data(dataset, my_ymin=None, my_ymax=None):
       ax=plt.subplot(111)
             if not my_ymin:
                ax.set_ylim(min(dataset),max(dataset))
             else:
                ax.set_ylim(my_ymin, my_ymax)
       ax.plot(dataset)

Upvotes: 1

Related Questions