Believe or not — even I don’t proclaim myself as good at Python programming, I can say have my fair share of reading Python codes — I didn’t know you can do this:
def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y
The code is from a Conway’s Game of Life clone. I only discovered it after running with Python 3:
$ python3 bin/conway.py File "bin/conway.py", line 23 def die((x, y)): ^ SyntaxError: invalid syntax
When I saw this error, I immediately spotted the (()) part and thought, this is interesting because I knew it runs normally with Python 2. I wondered what is going on here.
It turned out that has been removed from Python 3 via PEP 3113 — Removal of Tuple Parameter Unpacking. No, I didn’t start learning Python with Python 3, but Python 2 and I still didn’t know about Tuple Unpacking in function arguments. Maybe I did learn about it just never really learned it. Of course, never used it before and will never use it since it’s gone already in Python 3.
According the PEP, this syntax had very little usage in Python Lib/ at the time, only 0.18% of functions used tuple parameter.
Since it was going to be removed, it suggests and 2to3 would fix for:
def fxn((a, (b, c))): pass
with:
def fxn(a_b_c): (a, (b, c)) = a_b_c pass
Just unpack yourself would do fine for both Python 2 and 3.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.