Parsely / schemato

Modularly extensible semantic metadata validator
http://schema.to
Apache License 2.0
83 stars 9 forks source link

deepest_node is invalid syntax in Py2 and Py3? #20

Closed ghost closed 8 years ago

ghost commented 8 years ago

Working on porting for #19, but I've encountered this gem and I'm flummoxed:

def deepest_node((subj, pred, obj), graph):
    """recurse down the tree and return a list of the most deeply nested
    child nodes of the given triple"""
    # i don't fully accept the premise that this docstring presents
    # i'm not a docstring literalist
    to_return = []

    def _deepest_node((subj, pred, obj), graph):
        children = []
        if isinstance(obj, rt.BNode):
            for s, p, o in graph:
                if str(s) == str(obj):
                    children.append((s, p, o))
            for s, p, o in children:
                s1, p1, o1 = _deepest_node((s, p, o), graph)
                # coupling *smacks hand with ruler*
                if "rNews" in str(o1) and (s1, p1, o1) not in to_return:
                    to_return.append((s1, p1, o1))
            return (s1, p1, o1)
        else:
            return (subj, pred, obj)
    _deepest_node((subj, pred, obj), graph)

    return to_return

The idea of destructuring args is pretty cool, but it's not valid Python:

# Python 3
In [1]: def ((foo,bar,baz), qux):
  File "<ipython-input-1-c256cc6e9347>", line 1
    def ((foo,bar,baz), qux):
        ^
SyntaxError: invalid syntax
# Python 2
>>> def ((foo,bar,baz), qux):
  File "<stdin>", line 1
    def ((foo,bar,baz), qux):
        ^
SyntaxError: invalid syntax

..so how did this ever get into the source tree? And if it does work, how do I get it to work for me, because I like it in principle? :)

ghost commented 8 years ago

More:

E         File "/home/cathal/Projects/python/schemato/schemato/schemas/opengraph.py", line 45
E           def _is_instance(self, (subj, pred, obj)):
E                                  ^
E       SyntaxError: invalid syntax
dan-blanchard commented 8 years ago

PEP-3113 removed this sort of parameter unpacking, so that's why it doesn't work in Python 3.

The reason this appears not to work in Python 2 for you is that you forgot to name your function. 😄

# Python 2.7.12
In [1]: def packed_func((foo, bar, baz), qux):
   ...:     pass
   ...: 

In [2]: 
ghost commented 8 years ago

Thanks for the help! Yea, I'm not going to fight this one any further. I can see why they removed that syntax from Python, I guess; it's a nice feature in another language, but Python really doesn't need it, and I can see how it confuses matters.

And, whoops; I'm getting too used to anonymous functions and I keep making that error when I return to Python. :)