Using Python with Caché
Using the Python Binding
[Home] [Back] [Next]
InterSystems: The power behind what matters   

This chapter provides concrete examples of Python code that uses the Caché Python binding. The following subjects are discussed:

Many of the examples presented here are modified versions of the sample programs. The argument processing and error trapping (try/catch) statements have been removed to simplify the code. See Sample Programs for details about loading and running the complete sample programs.
Python Binding Basics
A Caché Python binding application can be quite simple. Here is a complete sample program:
   import codecs, sys
   import intersys.pythonbind

   # Connect to the Cache' database
   url = "localhost[1972]:Samples"
   user = "_SYSTEM"
   password = "SYS"

   conn = intersys.pythonbind.connection()
   conn.connect_now(url,user,password, None)
   database = intersys.pythonbind.database(conn)
   # Create and use a Cache' object
   person =  database.create_new("Sample.Person", None)
   person.set("Name","Doe, Joe A")
   print "Name: " + str(person.get("Name"))
This code imports the intersys.pythonbind module, and then performs the following actions:
The following sections discuss these basic actions in more detail.
Connecting to the Caché Database
The basic procedure for creating a connection to a namespace in a Cache database is as follows:
Using Caché Database Methods
The intersys.pythonbind.database class allows you to run Caché class methods and connect to Caché objects on the server. Here are the basic operations that can be performed with the Database class methods:
Using Caché Object Methods
The intersys.pythonbind.object class provides access to Caché objects. Here are the basic operations that can be performed with the Object class methods:
Passing Parameters by Reference
It is possible to pass arguments by reference with the Python binding. Since Python does not have a native mechanism for passing by reference, the binding passes all arguments as a list that can be modified by the called function. For example, assume the following Caché class:
   Class Caudron.PassByReference Extends %Persistent [ ProcedureBlock ] {
      ClassMethod PassByReference(ByRef Arg1 As %String) {
         set Arg1="goodbye"
The following code passes the argument by reference:
   list = ["hello"]
   print "passed to method PassByReference = " + str(list[0])
   print "returned by reference = " + str(list[0])
The print statements will produce the following output:
   passed to method PassByReference = hello
   returned by reference = goodbye
Using Collections and Lists
Caché %Collection objects are handled like any other Python binding object. Caché %List variables are mapped to Python array references. The following sections demonstrate how to use both of these items.
%Collection Objects
Collections are manipulated through object methods of the Caché %Collection class. The following example shows how you might manipulate a Caché %ListOfDataTypes collection:
   # Create a %ListOfDataTypes object and add a list of colors
   newcolors = database.create_new("%ListOfDataTypes", None)
   color_list = ['red', 'blue', 'green']
   print "Adding colors to list object:"
   for i in range(len(color_list)):
      print " added >"+ str(color_list[i]) +"<"

   # Add the list to a Sample.Person object.
   person = database.openid("Sample.Person",str(1),-1,0)

   # Get the list back from person and print it out.
   colors = person.get("FavoriteColors")
   print "\nNumber of colors in 'FavoriteColors' list: %d"\
      % (colors.get("Size"))
   index = [0]
   while (index[0] != None):
      color = colors.run_obj_method("GetNext",index)
      if (index[0] != None):
         print " Color #%d = >%s<" % (index[0], str(color))

   # Remove and replace the second element
   index = 2
   if (colors.get("Size") > 0):
   newcolor = colors.run_obj_method("GetAt",[index])
   print "\nChanged color #%d to %s." % (index, str(newcolor))
%List Variables
The Python binding maps Caché %List variables to Python array references.
While a Python array has no size limit, Caché %List variables are limited to approximately 32KB. The actual limit depends on the datatype and the exact amount of header data required for each element. Be sure to use appropriate error checking (as demonstrated in the following examples) if your %List data is likely to approach this limit.
The examples in this section assume the following Caché class:
   Class Sample.List Extends %Persistent
   Property CurrentList As %List;
   Method InitList() As %List { 
      q $ListBuild(1,"hello",3.14) }
   Method TestList(NewList As %List) As %Integer {
      set $ZTRAP="ErrTestList"
      set ItemCount = $ListLength(NewList)
      if (ItemCount = 0) {set ItemCount = -1}
      q ItemCount
      set $ZERROR = ""
      set $ZTRAP = ""
      q 0 }
The TestList() method is used to test if a Python array is a valid Caché list. If the list is too large,the method traps an error and returns 0 (Python false). If the list is valid, it returns the number of elements. If a valid list has 0 elements, it returns -1.
Example 1: Caché to Python
The following code creates a Sample.List object, gets a predefined Caché list from the InitList() method, transforms it into a Python array, and displays information about the array:
   listobj = database.create_new("Sample.List",None)
   mylist = listobj.run_obj_method("InitList",[])

   print "Initial List from Cache:"
   print "array contents = " + str(mylist)
   print "There are %d elements in the list:" % (len(mylist))
   for i in range(len(mylist)):
      print "   element %d = [%s]" % (i,mylist[i])
This code produces the following output:
   Initial List from Cache:
   array contents = [1, 'hello', 3.1400000000000001]
   There are 3 elements in the list:
      element 0 = [1]
      element 1 = [hello]
      element 2 = [3.14]
In element 3, the null list element in Caché corresponds to value of None in the Python array.
Example 2: Python to Caché and Back Again
The following code passes a list in both directions. It creates a small Python array, stores it in the Caché object's CurrentList property, then gets it back from the property and converts it back to a Python array.
   # Generate a small Python list, pass it to Cache and get it back.
   oldarray = [1, None, 2.78,"Just a small list."]
   newarray = listobj.get("CurrentList")
   print "\nThe 'CurrentList' property now has %d elements:"\
      % (len(newarray))
   for i in range(len(newarray)):
      print "  element %d = [%s]" % (i,newarray[i])
This code produces the following output:
   The 'CurrentList' property now has 4 elements:
      element 0 = [1]
      element 1 = [None]
      element 2 = [2.78]
      element 3 = [Just a small list.]
Example 3: Testing List Capacity
It is important to make sure that a Cache %List variable can contain the entire Python array. The following code creates a Python array that is too large, and attempts to store it in the CurrentList property.
   # Create a large array and print array information.
   longitem = "1022 character element" + ("1234567890" * 100)
   array =["This array is too long."]
   cache_list_size = len(array[0])
   while (cache_list_size < 32768):
      cache_list_size = cache_list_size + len(longitem)
   print "\n\nNow for a HUGE list:"
   print "Total bytes required by Cache' list: more than %d" % (cache_list_size)
   print "There are %d elements in the ingoing list.\n" % (len(array))
   # Check to see if the array will fit.
   bool = listobj.run_obj_method("TestList",[array])
   print "TestList reports that "
   if (bool):
      print "the array is OK, and has %d elements.\n" % bool
      print "the array will be damaged by the conversion.\n"

   # Pass the array to Cache', get it back, and display the results
   badarray = listobj.get("CurrentList")
   print "There are %d elements in the returned array:\n" % (len(badarray))
   for i in range(len(badarray)):
      line = str(badarray[i])
      if (len(line)> 80):
         # long elements are shortened for readability.
         line = line[:][:9] + "..." + line[:][-50:]
      print "   element %d = [%s]\n" % (i, line)
The printout shortens undamaged sections of the long elements to make the output more readable. The following output is produced on a unicode system:
Now for a HUGE list:
Total bytes in array: at least 33884
There are 34 elements in the ingoing array.
TestList reports that the array will be damaged by the conversion.
There are 17 elements in the returned array :
   element 1 = [This list is too long.]
   element 2 = [1022 chara...90123456789012345678901234567890]
   element 3 = [1022 chara...90123456789012345678901234567890]
   element 4 = [1022 chara...90123456789012345678901234567890]
   element 5 = [1022 chara...90123456789012345678901234567890]
   element 6 = [1022 chara...90123456789012345678901234567890]
   element 7 = [1022 chara...90123456789012345678901234567890]
   element 8 = [1022 chara...90123456789012345678901234567890]
   element 9 = [1022 chara...90123456789012345678901234567890]
   element 10 = [1022 chara...90123456789012345678901234567890]
   element 11 = [1022 chara...90123456789012345678901234567890]
   element 12 = [1022 chara...90123456789012345678901234567890]
   element 13 = [1022 chara...90123456789012345678901234567890]
   element 14 = [1022 chara...90123456789012345678901234567890]
   element 15 = [1022 chara...90123456789012345678901234567890]
   element 16 = [1022 chara...90123456789012345678901234567890]
   element 17 = [1022 chara...901234567st is too long.ï´√ȇ1022 c]
The damaged list contains only 17 of the original 34 elements, and element 17 is corrupted.
Using Relationships
Relationships are supported through the relationship object and its methods.
The following example generates a report by using the one/many relationship between the company object and a set of employee objects. The relationship object emp_relationship allows the code to access all employee objects associated with the company object:
   company = database.openid("Sample.Company",str(1),-1,0)
   emp_relationship = company.get("Employees")
   index = [None]
   print "Employee list:\n"
   while 1:
      employee = emp_relationship.run_obj_method("GetNext",index)
      # "GetNext" sets index[0] to the next valid index, or 
      # to None if there are no more records.
      if (employee != None):
         i = str(index[0])
         name = str(employee.get("Name"))
         title = str(employee.get("Title"))
         company = employee.get("Company")
         compname = str(company.get("Name"))
         SSN = str(employee.get("SSN"))
         print "   employee #%s:" % i
         print "      name=%s SSN=%s" % (name, SSN)
         print "      title=%s companyname=%s\n"% (title, compname)
The following code creates a new employee record, adds it to the relationship, and automatically saves the employee information when it saves company.
   new_employee = database.create_new("Sample.Employee","")
   emp_relationship.run_obj_method("Insert", new_employee)
Using Queries
The basic procedure for running a query is as follows:
For more information on the intersys.pythonbind.Query class, see Queries in the Python Client Class Reference chapter. For information about queries in Caché, see Defining and Using Class Queries in "Using Caché Objects".
Using %Binary Data
The Python binding uses the Python pack() and unpack() functions to convert data between a Caché %Binary and a Python list of integers. Each byte of the Caché binary data is represented in Python as an integer between 0 and 255.
In this example, the binary initially contains the string "hello". The following code changes the binary to "hellos":
   binary = reg.get("MyByte")
   for c in binary:
       print "%c" % c
   print type(ord("s"))
   binary = reg.get("MyByte")
   for c in binary:
       print "%c" % c
Handling Exceptions
The Python binding uses Python exceptions to return errors from the C binding and elsewhere. Here is an example using Python exceptions:
   #some code
except intersys.pythonbind.cache_exception, err:
    print "InterSystems Cache' exception"
    print sys.exc_type
    print sys.exc_value
    print sys.exc_traceback
    print str(err)
Error reporting
When processing an argument or a return value, error messages from the C binding are specially formatted by the Python binding layer. This information can be used by InterSystems WRC to help diagnose the problem.
Here is a sample error message:
   file=PythonBIND.xs line=71 err=-1 message=cbind_variant_set_buf()
   cpp_type=4 var.cpp_type=-1 var.obj.oref=1784835886
   class_name=%Library.RelationshipObject mtd_name=GetNext argnum=0
The error message components are:
file where the failure occurred.
line number in the file.
return code from the C binding.
message= cbind_variant_set_buf()
C binding error message.
cpp type of the method argument or return type.
variant cpp type.
variant oref.
class_name= %Library.RelationshipObject
class name of the object on which the method is invoked.
method name.
argument number. 0 is the first argument and -1 indicates a return value.

Send us comments on this page
Copyright © 1997-2019 InterSystems Corporation, Cambridge, MA