LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Auto-wrap python classes proof of concept

According to NI: Unfortunately, there is no direct way to call python class methods 

 

So we have to write static wrapper methods. I find this insufficiently imaginative for a highly dynamic language like python. So, presented with absolutely no warranty, is the attached wrapper script.

 

Say we want to use methods from classes defined in script.py:

class MyCounter:
    def __init__(self):
        self._count = 0
    def increment(self) -> None:
        self._count += 1
    def count(self) -> int:
        return self._count

 According to all the discussion I have found, we need to create wrapper methods like

def create_counter() -> MyCounter:
    return MyCounter()
def increment_counter(c: MyCounter) -> None:
    c.increment()
def count(c: MyCounter) -> int:
    return c.count()

Not fun! Can we generate these programmatically? Yes! We can programmatically generate wrappers when the script is imported into the LabVIEW python session and get the methods we expect without creating static wrappers:

avogadro5_0-1732171685039.png

We pass in "self" as the 1st argument for each method call. The only truly weird thing here is the "instantiate" method call which we need to generate a "self" argument for the __init__() constructor call (one area for improvement would be making a constructor function that doesn't need the explicit instantiation).

 

See generic_wrapper.py for details. The idea is you would replace "script" in "import script as module_to_wrap" with the script you want to wrap (I'm sure there's a way to parameterize this, left as an exercise for the reader...).

 

I'm sure there are tons of risks and edge cases to work out and other improvements so please improve this script!

 

0 Kudos
Message 1 of 1
(68 Views)