Transaction in Python

Sorry if the question has already been treated, but I couldn't find it.
Is it possible to do transactions in Python?
For instance, could we convert the following Ruby code into Python?

view = RBA::LayoutView::current

begin

  view.transaction("Restyle annotations")

  view.each_annotation do |a|
    a.style = RBA::Annotation::StyleArrowBoth
  end

ensure
  view.commit
end

Comments

  • edited July 2021

    Hi, Eric!

    Sure, KLayout's Python and Ruby classes are equivalent.

  • Thanks Eugene.

    My problem was rather that I could not find the equivalent of begin ensure end in Python.

    I must have had a foggy brain after a day at work, because this morning I found the answer in a few minutes on google. Sorry, next time I'll let a night pass before asking the question on the forum :)

    Here is the equivalent in Python. It works, but if it's not perfect, don't hesitate to let me know.

    view = pya.LayoutView.current()
    
    try:
    
      view.transaction("Restyle annotations")
    
      for a in view.each_annotation():
        a.style = pya.Annotation.StyleArrowBoth
    
    finally:
      view.commit
    
  • edited July 2021

    @ericjapon Almost perfect :)

    There is one important thing about Python: if you use a function without the brackets, it's not called! In your case that would spoil the undoability.

    So the last line has to have brackets:

    ...
    finally:
      view.commit()
    

    I made this mistake a couple of times myself :(

    Matthias

  • Thank you Matthias.
    Not the first time and probably not the last one I will do this one :(

Sign In or Register to comment.