Search code examples
pythonexcepttry-except

Try, Except:Pass on multiple lines


I'm writing another script for a program Called Abaqus, that plots XY data on a chart.... and part of my script changes the line styles based on if they are named a specific name....

So I have a bunch of different curve names and IF the chart contains that specific name, I want to execute the code to change the style... for example...

    session.curves[PathNameNew+'_S201-16'].symbolStyle.setValues(show=True)
    session.curves[PathNameNew+'_S201-16'].symbolStyle.setValues(marker=FILLED_DIAMOND)
    session.curves[PathNameNew+'_S201-16'].symbolStyle.setValues(size=2)
    session.curves[PathNameNew+'_S201-16'].symbolStyle.setValues(color='#009afb')
    session.curves[PathNameNew+'_S247-16'].symbolStyle.setValues(show=True)
    session.curves[PathNameNew+'_S247-16'].symbolStyle.setValues(marker=FILLED_DIAMOND)
    session.curves[PathNameNew+'_S247-16'].symbolStyle.setValues(size=2)
    session.curves[PathNameNew+'_S247-16'].symbolStyle.setValues(color='#009afb')
    session.curves[PathNameNew+'_RELEASE'].symbolStyle.setValues(show=True)
    session.curves[PathNameNew+'_RELEASE'].symbolStyle.setValues(marker=FILLED_DIAMOND)
    session.curves[PathNameNew+'_RELEASE'].symbolStyle.setValues(size=2)
    session.curves[PathNameNew+'_RELEASE'].symbolStyle.setValues(color='#009afb')   
    session.curves[PathNameNew+'_S205-18'].lineStyle.setValues(thickness=1)

I have about 50 different curve names with different styles and not all of those curves will be used every time, so I was thinking of using a Try, except:pass method to achieve this... however that would mean I would have to do that for EACH curve name...

Is there a better way?


Solution

  • You could always make a closure function to do it for you:

    def my_big_function():
        ...
        def set_symbolstyle_value(key, **kwargs):
            try:
                session.curves[PathNameNew + key].symbolStyle.setValues(**kwargs)
            except MyException:
                do_something()
    
        set_symbolstyle_value('_S201-16', show=True)
        set_symbolstyle_value('_S201-16', marker=FILLED_DIAMOND)
        ...
    

    Functions are cheap. Don't be afraid to use them.