[Pyrex] Circular cimports

Lenard Lindstrom len-l at telus.net
Sat Jun 10 22:16:37 UTC 2006


On 10 Jun 2006 at 14:10, Mike Wyatt wrote:

> 
> In C/C++, I believe this problem would be solved like this:
> 
> **matrix.h**
> #ifndef MATRIX_H
> #define MATRIX_H
> 
> /* declarations here */
> #endif
> 
> **matrix.c**
> #include "matrix.h"
> 
> /* implementation here */
> 
> Is there an equivalent to #ifndef in Pyrex? Or is there any other 
> solution to my problem?

This is quite a different thing. It prevents a C/C++ .h file from 
being included more than once for a given .c/.cpp file. What you are 
trying to do is more like a forward declaration. I don't know if that 
works for Pyrex extension types. In Python it is not a problem since 
duck typing is used. That is, you just accept some object and call 
methods on it. If they are there things work, if not a runtime 
exception is raised. So you could break the cycle by having the 
Vector method accept a Matrix like object and just call the expected 
python methods on it. You will have to import the matrix module into 
vector, but not vector into matrix.

Alternatively you could try creating root matrix and vector classes 
that know nothing about each other, then created subclasses of each 
that have additional methods that manipulate the root class of the 
other.

>     I'm building a little math library in Pyrex, and I'm having trouble 
>     with some circular cimports. I'll post short excerpts from my 
>     various files, then show the error that I'm getting when I try to use 
>     one of the modules.
>     
>     **matrix.pxd**
>     cdef class Matrix:
>      cdef float m[4][4]
>     
>     **matrix.pyx**
>     cimport vector
>     
>     cdef class Matrix:
>      ### a bunch of methods, including ones that create or manipulate 
>     Vector objects ###
>     
>     **vector.pxd**
>     cdef class Vector:
>      cdef float x, y, z, w
>     
>     **vector.pyx**
>     cimport matrix
>     
>     cdef class Vector:
>      ### a bunch of methods, including one that has a Matrix argument 
>     ###
>     
>     After building the Pyrex modules into .pyd files, I run a test 
>     module.The first line imports the matrix module and throws this 
>     error:
>     
>     Traceback (most recent call last):
>      File "C:\Development\SFStratPrototype\math3d\matrixTest.py", line 
>     1, in ?
>      import matrix
>      File "vector.pxd", line 1, in matrix
>      cdef class Vector:
>      File "matrix.pxd", line 1, in vector
>      cdef class Matrix:
>     AttributeError: 'module' object has no attribute 'Matrix'
>     Press any key to continue . . .
>     
>     It doesn't seem to like how the modules cimport each other. I can't 
>     see any way to eliminate this circular reference, so what can I do to 
>     fix this error?


Lenard Lindstrom
<len-l at telus.net>





More information about the Pyrex mailing list