WhiteTiger WhiteTiger - 11 months ago 67
Python Question

Strange syntax error with theano

I'm trying to use theano in my code right now in python 3.4. However, there are many function with the following strange syntax

def c_code(self, node, name, (var1, var2), (var3,), sub):

i.e. they have brackets within the function definition.

Python throws a syntax error on them

File ".../Theano-0.7.0/theano/scalar/basic.py", line 1011

def c_code(self, node, name, (var1, var2), (var3, ), sub):

SyntaxError: invalid syntax

Now, once I remove those extra brackets, everything works great, but I'm new to python and noticed there were a lot of changes in python 3 so these brackets may need to be replaced with something else rather than removed.

Can someone explain to me (a) what having brackets inside function definition means? and (b) if and how can these be made to work with python 3?

Answer Source

Tuple argument unpacking has been removed in Python 3.0 via PEP3113:

Tuple parameter unpacking is the use of a tuple as a parameter in a function signature so as to have a sequence argument automatically unpacked. An example is:

def fxn(a, (b, c), d):

The use of (b, c) in the signature requires that the second argument to the function be a sequence of length two (e.g., [42, -13] ). When such a sequence is passed it is unpacked and has its values assigned to the parameters, just as if the statement b, c = [42, -13] had been executed in the parameter.

Unfortunately this feature of Python's rich function signature abilities, while handy in some situations, causes more issues than they are worth. Thus this PEP proposes their removal from the language in Python 3.0.

So if you take this function signature

def fun(foo, (a, b, c), bar):

then that is equivalent to

def fun(foo, arg, bar):
    a, b, c = arg

so that's the way you would achieve the same behavior with Python 3.x.

However, since this is not your own code base, I don't see an easy way of addressing that (short of monkey patching), and there might also be more Python 3 incompatibilities that aren't as easily spotted as SyntaxErrors.

Interestingly enough, issue #783 linked by @tobias_k has been closed, and from it it seems that Python 3 support has been addressed and finished. Also, Theano does claim Python 3 support according to it's Trove classifiers.

However, the version you're using (0.7.0) is the most recently released one, and the function signature you encountered is in fact still to be found on current master. So - this is a bug, you should probably file an issue on Theano's GitHub issue tracker.