[Pyrex] Initialization problem

Valentino Volonghi aka Dialtone dialtone at divmod.com
Fri Aug 11 01:35:34 UTC 2006


I find myself in the following situation:

cdef class Document:
    cdef ESTDOC *estdoc
    
    def __new__(self, uri):
        self.estdoc = est_doc_new()
        self['@uri'] = uri

I need to initialize this Document class using an uri argument.

Unfortunately I also need to initialize this object without passing a uri argument (but the user should always be asked an uri object).

Initially I used:

cdef class Document:
    cdef ESTDOC *estdoc

    def __new__(self, uri, ESTDOC *edoc):
        if edoc == NULL:
            self.estdoc = est_doc_new()
            self['@uri'] = uri
        else:
            self.estdoc = edoc

but this didn't actually work because ESTDOC * would be exposed to the user and there's no way to translate a python object to an ESTDOC * automatically.

I then decided to do the following:

cdef class Document:
    cdef ESTDOC *estdoc

    def __new__(self, uri):
        self.estdoc = est_doc_new()
        self['@uri'] = uri

    cdef set_new_estdoc(self, ESTDOC *edoc):
        est_doc_delete(self.estdoc)
        self.estdoc = edoc

This works but as you see requires that I call est_doc_delete any time I need to build a Document object without a predefined uri attribute.

Another partial solution could be to do the following:

cdef class Document:
    cdef ESTDOC *estdoc
    
    def __new__(self, uri):
        if uri != None:
            self.estdoc = est_doc_new()
            self['@uri'] = uri

    cdef set_new_estdoc(self, ESTDOC *edoc):
        self.estdoc = edoc

But in this way there is a little chance to have self.estdoc == NULL in the method calls if the user calls Document(None). I'd be glad to be able to do
Document(NULL) internally but unfortunately uri is a Python object and NULL cannot be used with Python objects.

How do you suggest proceeding in order to completely hide this implementation detail from the user but still preserving it?

Currently I'm going for this last solution with a check for self.estdoc being always != NULL before any method call. It's by far the least expensive but if you have some suggestions I'd be glad.

Thanks.



More information about the Pyrex mailing list