Python plugin question: Wrap functions in a class?

Is there any obstacle to bundling my pythyon plugin functions into a single class?

I finally converted most of my backend Lua code base into python and am now working on cleaning up the python scripts. Currently, I have many standalone functions and some global variables to control global behavior. My thought is that I could convert to a class and make the global variables become members of the class - hence available to all member methods.

All of the examples in the python plugin documentation reference standalone python functions.

To bundle all my functions in a class, I think I would need the ability to:

  • Bind to class methods:
    orthanc.RegisterRestCallback(‘/some/url’, myclass.mymethod)
  • Instantiate my class with some trigger
    • orthanc.ChangeType.ORTHANC_STARTED
    • I am thinking I would need some form of instantiation to pre-populate some class members with values that are currently managed by global variables with the standalone function approach. But maybe I don’t need instantiation?

Thanks,
John.

Hi John,

Here’s a sample in which the main part of the code is in a class but I still have some “glue” code to make the interface between the plugin callbacks and the class.

I have actually never tried to configure a plugin callback to a python class member.

One of the big advantage of this “class” approach is that you can make your class runnable outside the orthanc plugin which ease debugging a lot !!!

HTH,

Alain

Hi John,

I wrote a small Python framework that is meant to support your use case to easily write unit / integration testable event triggers. It allows you to register plain python functions (both sync as well as async) as event handlers. Event driven programming comes with some common challenges, so I’m planning to add some more tutorials to demonstrate how more complex use cases like pipelines, injecting configuration and multiple triggers can be solved.

I already have an example where a function gets pre-populated with a global config object, that seems to answer your specific question.

You can find the project on Github and PyPI.

Let me know if you find it useful, if only for inspiration :slight_smile:

Regards
Walco

Dear Walco,

Thanks for your great work on this topic! I feel like your Orthanc Server Extensions would be an excellent topic for a talk at the Orthanc conference next month (remote presentations are possible). What would you think of this opportunity?

Kind Regards,
Sébastien-

Hi Sébastien!

In fact I was seriously considering that. Recently I added asyncio support to the library, which could make an interesting topic for the conference, although a more entry level talk is possible as well. I will write a short proposal.

Regards
Walco

Great, looking forward to this!

Sébastien-