How to make it easier not to create a lot of conditions if elif

Question:

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

Asked By: Michael

||

Answers:

You can use getattr

plot = getattr(axs, type_)(x, y)
Answered By: jprebys
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.