Ask Your Question

UNO: check instance of an UNO object in python

asked 2019-07-20 19:45:09 +0200

Hi-Angel gravatar image

As part of solving this question I want to be able to check whether an object property is instance of a certain class to ignore it.

So, if I have a slide object (i.e. XDrawPage), and I do type(slide1.getByIndex), I get:

<class 'PyUNO_callable'>

How can I use that with isinstance()? If I do isinstance(slide1.getByIndex, PyUNO_callable), I get:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'PyUNO_callable' is not defined

So far I tried: using pyuno.getClass('PyUNO_callable') (it throws an exception), and asking on #python IRC, to no avail.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2019-07-20 20:28:32 +0200

Hi-Angel gravatar image

updated 2019-07-20 20:33:01 +0200

It's more of a workaround, but better than nothing. After talking on #python, turned out, type() python function returns the type itself, not a string! So, as a workaround, you might be able to get the type from something you always has around, and then use that to compare. Here's a demo:

import uno

# run libreoffice as:
# soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

def connectToLO():
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "", localContext )
    # connect to the running office
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "",ctx)
    return desktop.CurrentComponent

model = connectToLO()

TYPE_UNO_CALLABLE = type(model.getPropertyValue)
# Example assumes you have the ActiveSheet.getColumns, which is available in LO
# Calc. I've used that to have something different from `model` to compare.
if isinstance(model.CurrentController.ActiveSheet.getColumns, TYPE_UNO_CALLABLE):
    print('Hey, it works!')
    print("it doesn't work ☹")

In shell:

$ python
Hey, it works!
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2019-07-20 19:45:09 +0200

Seen: 28 times

Last updated: Jul 20