Prob. Code Downloaded for Programming the Semantic Web (python code)

Steven D'Aprano steve+gmane at pearwood.info
Sat Jul 26 03:28:32 CEST 2014


On Fri, 25 Jul 2014 17:06:17 -0700, Bruce Whealton wrote:

> OK, Eclipse with PyDev doesn't like this first line, with the function:
> def add(self, (sub, pred, obj)):

In Python 2, you could include parenthesised parameters inside function
declarations as above. That is effectively a short cut for this version,
where you collect a single argument and then expand it into three
variables:

    def add(self, sub_pred_obj):
        sub, pred, obj = sub_pred_obj


In Python 3, that functionality was dropped and is no longer allowed. Now
you have to use the longer form.

[...]
> There are other places where I thought that there were too many
> parentheses and I tried removing one set of them.  For example this
> snippet here:
> 
>     def remove(self, (sub, pred, obj)):
>         """
>         Remove a triple pattern from the graph. """
>         triples = list(self.triples((sub, pred, obj)))

Firstly, the remove method expects to take a *single* argument (remember
that self is automatically provided by Python) which is then automatically
expanded into three variables sub, pred, obj. So you have to call it with a
list or tuple of three items (or even a string of length exactly 3).

Then, having split this list or tuple into three items, it then joins them
back again into a tuple:

    (sub, pred, obj)

passes that tuple to the triples method:

    self.triples((sub, pred, obj))

(not shown, but presumably it uses the same parenthesised parameter trick),
and then converts whatever triples returns into a list:

    list(self.triples((sub, pred, obj)))

that list then being bound to the name "triples".


> Are the two sets parentheses needed after self.triples?  That syntax is
> confusing to me.  It seems that it should be triples =
> list(self.triples(sub, pred, obj))

It's needed because the triples method is written 

    def triples(self, (sub, pred, obj)):

instead of the more obvious:

    def triples(self, sub, pred, obj):



-- 
Steven





More information about the Python-list mailing list