python extension problem (newbie)
Gordon McMillan
gmcm at hypernet.com
Wed Jun 2 00:01:41 EDT 1999
Douglas du Boulay writes:
>
> I've been trying to write a python extension in C to interface to a
> Fortran program and a class wrapper for the extension using the
> following code loosely adapted from Mark Lutz's Programming Python
> stackmodule example.
>
> Unfortunately whereas his example works fine, mine goes into a
> recursive loop whenever an instance is instantiated. It seems that
> the __getattr__ method of the wrapper class cannot find the getattr
> method of the extension library and defaults to trying to call
> itself, infinitely recursively.
You didn't need an extension module to do this. It's all in the
wrapper. While __getattr__ is only called if an appropriate attribute
is not found, __setattr__ is *always* called when trying to set an
attribute.
So the assignment to self._base in __init__ invokes __setattr__
recursively. A print statement (the only one you're missing, of
course) will prove this (and make you go boom in slow motion).
If you use __setattr__, you need to do all your assignments (in
methods of the class like this:
self.__dict__['_base'] = start or p2fgraspint.Grasp()
(I do this about half the time I use __setattr__. Now you'll know
what to look for, too).
> >>file oograsp.py
>
> import p2fgraspint
>
> class Grasp:
> def __init__(self, start=None):
> self._base = start or p2fgraspint.Grasp()
> print "doing done" # which is never
> executed
> def __getattr__(self, name):
> print "called getattr" # executed endlessly
> return getattr( self._base , name)
> def __setattr__(self, name, value):
> return setattr(self._base, name, value)
>
> >> file http://www.crystal.uwa.edu.au/~ddb/pyextend/p2fgraspint.c
>
> >> file graspsub.py
>
> #!/usr/bin/env python
> import oograsp
> x = oograsp.Grasp()
>
>
>
- Gordon
More information about the Python-list
mailing list