简体   繁体   中英

Python argument unpacking

Sometimes, some functions exchange some really ad-hoc tuples of data.

>>> def foo():
...    return (1,2,4)
...
>>> def f(a, b, v):
...    x, y, z = v
...    # ...
...    # suppose there are 2-4 lines of some trivial code
...    # ...
...    print a, b, '(', x, y, z, ')'
...
>>> f(1, 2, foo())
1 2 ( 1 2 4 )

The use-case here is that it's really ad-hoc bunch of data, so we don't want to introduce a new class. (We also assume that the tuple itself is just a bunch of data, so that accessing the tuple's elements by index, like print a, b, '(', v[0], v[1], v[2], ')' would be really confusing to the reader.)

So, anyway. We decided to pass tuples around, and we want to unpack (deconstruct) them. What's cool, is that you can unpack an argument-tuple right in the function's argument list, so f can be simplified just a bit:

>>> def f(a, b, (x,y,z)):
...    # ...
...    # the same implementation
...    # ...
...    print a, b, '(', x, y, z, ')'

It makes it a bit cleaner to the reader. It's just one line of code, but it's also completely unnecessary code, and it also make the function's signature look cleaner.

Is there are any hidden pitfalls of this technique? Is it a generally frowned upon feature (in which case I'm interested in the reason)?

I use python 2.7. Thanks!

In Python3, the Tuple Parameter Unpacking feature is removed . Per PEP 3113:

Unfortunately this feature of Python's rich function signature abilities, while handy in some situations, causes more issues than they are worth.

So don't use it; it will make your code Python2-compatible only. Other reasons to avoid tuple parameter unpacking which are discussed in the PEP include

  • Introspection Issues
  • No Loss of Abilities If Removed
  • Exception To The Rule
  • Uninformative Error Messages
  • Little Usage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM