Selective Import

To selectively import namespace components, use gi-import-by-name, which takes two arguments, a namespace and a (component) name. Let’s try on our minimal ‘Hello World!’ example and see how it goes. All we need to do, is to substitute the (gi-import "Gtk") call by the following expression:

(for-each (lambda (name)
            (gi-import-by-name "Gtk" name))
    '("Application"
      "ApplicationWindow"
      "Button"))

With this change, everything else kept equal, if you (quit and) restart Guile, evaluate the updated ‘Hello World!’ example code, you will notice how the elapse time before the application window appears is now substantially reduced, compared to the version that imports the all Gtk namespace. Substantially reduced but … not instantaneous: well, that is expected!

Although we only import a few Gtk namespace components, three GObject classes in this example, G-Golf will import those classes, their interface(s) if any, methods, enums, flags ... and do the same for their parent class, recursively. For those three classes only, G-Golf actually has to import (and dynamically define) tens of classes, interfaces, enums, flags … as well as hundreds of methods and procedures.

G-Golf will also import classes, interfaces and their dependencies (enums, flags … recursively as well …) from other namespace if necessary. We already have an illustration of this, both with the original example and the change we just made: although we do not explicitly import the GApplication class from the Gio namespace, G-Golf did that for us, and so we may call run - which is the short method name for g-application-run - as if we did manually import it.

Both the namespace and name arguments are case sensitive. The name argument is used to retrieve the typelib Base Info that holds the metadata of the introspectable library element it represents. Although there are a some exceptions, it is generally derived from and obtained by dropping the namespace prefix (without its version number if any) out of the original name. Here are a few more examples, organized by namespace:

Gtk

GtkWindow -> Window
gtk_init -> init
gtk_main -> main
gtk_main_quit -> main_quit

WebKit2

WebKitWebView -> WebView
WebKitLoadEvent -> LoadEvent

  _ Cool, selective import, but what about scripting?

Right! The ’Hello World!’ example we have presented so far can only be run interactively.

In the next section, we will see how we may turn it - and any other example or application - so it can be run as a script.