[Zope] Path expression in Python based script

Paul Winkler pw_lists at slinkp.com
Fri Sep 29 09:43:00 EDT 2006


On Fri, Sep 29, 2006 at 09:00:16AM +0200, Daniel de la Cuesta wrote:
> path="animals"
> items=len(context.sections.path.contentValues())
> 
> 
> When I try to run the script I get an error saying that the variable "path" is not present.
> 
> If i do:
> 
> items=len(context.sections.animals.contentValues())
> 
> everything is ok,
> 
> How can I refer to a variable into a path expression in a Python Based Script?

On the surface this isn't really a zope question, it's basic Python.
You're looking for the getattr() builtin function.  For example:

pw at kermit ~ $ python
Python 2.4.3 (#1, Jul 27 2006, 13:07:44)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     bar = 1
...
>>> foo = Foo()
>>> foo.bar
1
>>> path = 'bar'
>>> foo.path
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Foo instance has no attribute 'path'
>>> getattr(foo, path)
1


Of course, Zope 2 has to complicate things a bit :)
Zope's ObjectManagers, such as Folders, also allow you
to use dictionary syntax to access their children.
So you can do foo[path] as well.

There is a semantic difference, though, in Zope 2: 

* attribute access like getattr(foo, 'bar'),  or foo.bar, falls
  back to using acquisition to look for 'bar' in foo's parent
  folders.

* Item access (like foo['bar']) does not use acquisition, so you'd get an
  immediate KeyError if foo does not contain the named object.

I recommend using item access in all cases except when you know
for sure that you want to use acquisition. Acquisition bugs can be big
time-wasters - e.g. accidentally acquiring a slightly different object
than the one you wanted to use, because the one you expected to find
happens to be missing, or a site admin renamed it, or some such.

-- 

Paul Winkler
http://www.slinkp.com


More information about the Zope mailing list