Alexey Zakhlestin's Blog

Programming for Mac and Web

Using Python With GObject Introspection

Permalink

I was recently working on one small tool for Midgard Project, and had to deal with a new framework: PyGI. Strictly speaking, it’s not “totally new”, but it is: a) new for me b) just starts to get attention from application developers.

PyGI is a project, which implements dynamic bindings to GObject based libraries for Python using GObject Introspection. Initially, it was a separate project, these days it is merged into main PyGObect. If you read my previous posts, this is kinda what we want to implement for PHP in GObject for PHP project, but for Python.

For the project, I used Python 3. This choice led to the requirement of installing latest versions of software, but the good news is, that coming Ubuntu Natty has a good initial set of software. So, I had to install:

The main library, I worked with — libmidgard2 — supports GObject introspection, so I didn’t need to install anything python-related to make it work.

Ok. Here are some hints on coding using PyGI.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    # to use introspection-friendly library use import statement similar to this
    from gi.repository import Midgard

    # global functions are available directly in imported package
    Midgard.init()

    # constructors are ALWAYS called with "named" parameters
    config = Midgard.Config(dbtype = "SQLite", database = "testdb")

    # library errors are thrown as exceptions
    import gobject
    try:
        do_something()
    except gobject.GError as e:
        print(e.message)

    # want to know name of objects GType?
    print(obj.__class__.__gtype__.name)

    # want to get list of non-object properties of some GObject?
    property_names = [pspec.name for pspec in obj.props if not pspec.value_type.is_classed()]

    # need to get names of all classes, which inherit from your GObject's class?
    # (note: Midgard.Object is the class to be replaced by your class)
    child_names = [gtype.name for gtype in Midgard.Object.__gtype__.children]

Comments