Unpacking Python Arguments

Sometimes, some functions exchange some really special data tuples.

>>> 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 )

      

In this case, we are talking about the fact that this is really a special data group, so we do not want to introduce a new class. (We also assume that the tuple itself is just a bunch of data, so accessing the elements of a tuple by index, for example print a, b, '(', v[0], v[1], v[2], ')'

, will be really confusing for the reader.)

So, anyway. We decided to pass the tuples around and we want to unpack them (deconstruct). The great thing is that you can unpack a tuple of arguments right in a function's argument list, so f

you can simply simplify:

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

      

This makes it cleaner for the reader. This is just one line of code, but it is also completely unnecessary code and also makes the function signature cleaner.

Are there hidden pitfalls of this technique? Is this generally a disapproving feature (in which case I'm interested in the reason)?

I am using python 2.7. Thank!

+3


source to share


1 answer


In Python3, the Parameter Unpacking feature is disabled . On PEP 3113:

Unfortunately, this feature of Python function-enabled signing capabilities, while handy in some situations, causes more problems than they are worth.



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

  • Introspection problems
  • Without losing opportunities
  • Exception to the rule
  • Informative error messages
  • Little use
+5


source







All Articles