[redland-dev] Problem: removing triple without specifying triple's object

Danny Ayers danny.ayers at gmail.com
Tue Jul 19 10:55:57 BST 2005


On 7/19/05, Dave Beckett <dave.beckett at bristol.ac.uk> wrote:
>  In mozilla I think they have an updateObject
> method something like:
>   model.updateObject(subject, predicate, oldObject, newObject)
> 
> but maybe an updateStatement one would work better for redland:
> 
>   model.updateStatement(oldSt, newSt)

I've no idea what the best answer would be, but soon after starting
playing with Redland/Python I found it convenient to set up the
utility class listed below, to provide a

set_target(model, source, predicate, target) 

method where the code enforces that there can only be one statement
with the specified subject, predicate. i.e. comparable to a regular OO
setter method. (I'm not using contexts, yet...) The way I've written
it is undoubtedly unpythonic (probably buggy too), I was using Jena
previously and had a very similar utility method there.

Note that I originally intended the remove_all method to provide a
general simple pattern-based delete, working something like
RDF.find_statements(Statement(s, p, o)). But I've still not had a
pressing need for anything other than delete(s, p, *)

Cheers,
Danny.


from RDF import Statement,Node

def get_first_target(model, source, predicate):
    try:
        iterator = model.get_targets(source, predicate)
    except Exception:
        return None
    node = iterator.current()
    iterator = None
    return node

def set_target(model, source, predicate, target):

# these didn't make life any easier
##     try:
##         source.is_resource()
##     except Exception:
##         source = Node(source)

    remove_all(model, source, predicate)
    model.append(Statement(source, predicate, target))

def remove_all(model, source=None, predicate=None, target=None):
    if source and predicate and (not target):
        try:
            iterator = model.get_targets(source, predicate)
        except: # no matching statements
            return
        while not iterator.end():
            target = iterator.current()
            del model[Statement(source, predicate, target)]
            iterator.next()
        iterator=None   

http://dannyayers.com/svn/pragmatron/sparqlsphere/redland_helpers.py

-- 

http://dannyayers.com


More information about the redland-dev mailing list