[Zope] Modifying a Dictionaries in an Extenal Method

Dieter Maurer dieter at handshake.de
Sun Jun 5 15:52:05 EDT 2005


Edward Huixquic wrote at 2005-6-5 00:05 -0500:
> ...
><dtml-if process >
>   <dtml-in fields mapping>
>      <dtml-call "pyUpdate(REQUEST)">

Why do you call "pyUpdate" in a loop?

> ...
>Name: <input type="text" name="fields.name:records" value="Mickey"><br>

Thus "fields" becomes a list of "ZPublisher.HTTPRequest.record"
objects.

> ...
>Python External Method:
>def pyUpdate(self,REQUEST):
>    for item in range(len(self.REQUEST['fields'])):
>        self.REQUEST['x']=self.REQUEST['fields'][0]
>        self.REQUEST['y']=self.REQUEST['fields'][1]
>#       self.REQUEST['fields'][0]['balance']=5000    <-----I will
>refer to this as first line
>#       self.REQUEST['y']['balance']=5000       <-------- this would
>be the second line
>    return self.REQUEST

Ouch! This code hurts my eyes!

I suggest, you avoid code duplication -- this is more efficient
and more readable:

def pyUpdate(self,REQUEST):
    fields = REQUEST['fields']
    for item in range(len(fields)):
        REQUEST['x'] = fields[0]
        y =REQUEST['y'] = fields[1]
	fields[0].balance = 5000
	y.balance = 5000

This is not much more readable, isn't it?

It is still stupid to execute the assignments in a loop (as
they are indepentent of the loop variable) but I assume
that you simple provides some example code (you hopefully
do not use in your real program).

> ...
>y	{'balance': '2000', 'lastname': 'Duck', 'name': 'Donald'}
>x	{'balance': '1000', 'lastname': 'Mouse', 'name': 'Mickey'}
>
>So, fields behaves as a list and X and Y are dictionaries, right?

They look like dictionaries but are in
fact "ZPublisher.HTTPRequest.record" instances.

> ...
>--------------------------------------------------------------------------------------
>Output with first line the python external methods NOT commented out:
> ....
>    * Module Products.ExternalMethod.ExternalMethod, line 232, in __call__
>      __traceback_info__: ((<HTTPRequest,
>URL=http://mo2:8080/mytestfolder/modules/test1>,), {}, None)
>    * Module /usr/local/Zope-2.7.4/instance1/Extensions/generator.py,
>line 577, in pyUpdate
>    * Module ZPublisher.HTTPRequest, line 1502, in __getattr__
>
>AttributeError: __setitem__


The reason for this error is that "record" objects
do not support item assignment (although otherwise they try to emulate
dictionaries). Use "record.attr = value" rather than
"record['attr'] = value".

-- 
Dieter


More information about the Zope mailing list