Home > Software design >  How to make it easier not to create a lot of conditions if elif
How to make it easier not to create a lot of conditions if elif

Time:10-19

def add_plot(axs, type_, x, y, y1=None, y2=None, height=None):
    try:
        if type_ in ['plot', 'scatter', 'stem', 'step']:
            _plot, = axs.plot(x,y)
            # but if type_ == 'scatter', I wouldn't want to write a separate condition for each type_
            # would like something like
            _plot, = setattr(axs, type_, {'x':x,'y':y})
    except Exception as e: 
        print(str(e))

Help, can anyone know the solution, thanks in advance

CodePudding user response:

You can use getattr

plot = getattr(axs, type_)(x, y)
  • Related