16.8.2. Modules

In the GRT Modules are libraries containing a list of functions that are exported for use by code in other modules, scripts or Workbench itself. Modules can currently be written in C++, Lua or Python, but the data types used for arguments and the return value must be GRT types.

GRT modules are similar to Python modules. They are however imported from the built-in grt module, instead of directly from an external file. The list of modules loaded into the grt module is obtained grt.modules. Modules can be imported in Python using statements such as from grt.modules import WbModel.

To export functions as a module from Python code you need to carry out the following:

  1. The source file must be located in the user modules folder. This path is displayed in the Workbench Scripting Shell with the label Looking for user plugins in.... It is also possible to install the file using the main menu item Scripting, Install Plugin/Module File.

  2. The source file name must have the extension _grt.py, for example, my_module_grt.py.

  3. Some module metadata needs to be defined. This can be done using the DefineModule function from the wb module:

    from wb import *
    ModuleInfo = DefineModule(name='MyModule', author='Your Name', version='1.0')
  4. Functions to be exported require their signature to be declared. This is achieved using the export decorator in the previously created ModuleInfo object:

    @ModuleInfo.export(grt.INT, grt.STRING)
    def checkString(s):

    Note, for the export statement, the return type is listed first, followed by the input parameter types. These types are specified as GRT typenames. The typenames that can be used are as follows:

    • grt.INT: Integer values. Also used for boolean values.

    • grt.DOUBLE: Floating-point numeric values.

    • grt.STRING: UTF-8 or ASCII string data.

    • grt.DICT: A key/value dictionary item. Keys must be strings.

    • grt.LIST: A list of other values. It is possible to specify the type of the contents as a tuple in the form (grt.LIST, <type-or-class>). For example, (grt.LIST, grt.STRING) for a list of strings. For a list of table objects the following would be specified: (grt.LIST, grt.classes.db_table).

    • grt.OBJECT: An instance of a GRT object or a GRT class object, from grt.classes.

    Note these types are defined in the grt module, which must first be imported before they can be used.

The following code snippet illustrates declaring a module that exports a single function:

from wb import *
import grt
ModuleInfo = DefineModule(name='MyModule', author="your name", version='1.0')
@ModuleInfo.export(grt.DOUBLE, grt.STRING, (grt.LIST, grt.DOUBLE))
def printListSum(message, doubleList):
   sum = 0
   for d in doubleList:
      sum = sum + d
   print message, sum
   return sum   
Copyright © 2010-2023 Platon Technologies, s.r.o.           Index | Man stránky | tLDP | Dokumenty | Utilitky | O projekte
Design by styleshout