[Zope] How to define class in Python script instance?

Skip Montanaro skip@pobox.com
Sat, 23 Nov 2002 15:11:20 -0600


I'm struggling to understand how <dtml-tree> is supposed to work with Python
scripts.  I have this simple dtml document:

    <dtml-var standard_html_header>
    <h2><dtml-var title_or_id></h2>

      <dtml-tree id="id" branches_expr="utils.get_tree()">
        <b><dtml-var name></b> <dtml-var id>
      </dtml-tree>

    <dtml-var standard_html_footer>

utils.get_tree() is a simple Python script:

    sql = context.sql

    class dummy: pass

    result = []
    for obj in sql.get_client_names().dictionaries():
        d = dummy()
        d.name = obj["name"]
        d.id = obj["id"]
        result.append(d)
    result.sort()
    return result

(The problem I'm trying to solve is more complex than the above simple
example suggests.  I have a hierarchy of tables in my SQL database, so
sql.get_client_names() isn't the only ZSQL method which needs to be called.
The different methods return objects with different field names.)

If I understand anthony's tree-coding-tricks document, <dtml-tree> can't
handle mappings, so you have to return lists of objects with attributes.
When my Python script is called I get this error:

    Error Type: TypeError
    Error Value: attribute-less object (assign or del)

with reference to the d.name = ... statement.  I tried defining the dummy
class as:

    class dummy:
        def __init__(self, name, id):
            self.name = name
            self.id = id

but Zope complained about defining a variable with two leading underscores.
Do I have to create an external method to define classes?  The Zope Book
suggests that's really not possible either:

    Problems can occur if you hand instances of your own classes to
    Zope and expect them to work like Zope objects. For example, you
    cannot define a class in an External Method script file and assign
    it as an attribute of a Zope object. This causes problems with
    Zope's persistence machinery. You also cannot easily hand
    instances of your own classes over to DTML or scripts. The issue
    here is that your instances won't have Zope security
    information. You can define and use your own classes and instances
    to your heart's delight, just don't expect Zope to use them
    directly. Limit yourself to returning simple Python structures
    like strings, dictionaries and lists or Zope objects.

So what's a poor fella to do?

Thx,

-- 
Skip Montanaro - skip@pobox.com
http://www.mojam.com/
http://www.musi-cal.com/