Python Newbie needs help with object cleanup in Finally

I’m writing my first Python script. It goes through various steps, adding to a drawing. At the end I want to remove some temporary objects it has created from the drawing, leaving just the ultimate element. I have put delete commands in the Finally clause to do the cleanup. I intended to check for the presence of each object before attempting to delete it but I obviously haven’t go that right because I get an error.

Code is along these lines:

Def TooCleverByHalf()
        line1 = rs.AddLine(ptA1f, ptB1f)
        if isGubbins() :
        line2 = rs.AddLine(ptA2f, ptB2f)
    Except :
    Finally :
        if line1 : rs.DeleteObject(line1)
        if line2 : rs.DeleteObject(line2)

If isGubbins is true then I exit the Try section and don’t create line2. When the Finally section executes I get the error:

    Message: Local variable 'line2' referenced before assignment.

Is there a tidy way to do the cleanup as I wish?

At the begin of your function before you do anything add

line1 = None
line2 = None

That will ensure line2 exists even in the finally.

Hmm, simple if not elegant. Perhaps I can sneak in some type definitions at the same time :wink:


Not elegant maybe, but you have a return before the first assignment of line2. When that path is chosen (isGubbins() evaluates to True) you get the mentioned error.

True, but don’t worry, an inelegant solution will blend well with my inelegant code. The start of a new language, the start of a long journey…

1 Like