Sunday, February 25, 2007

Pythons Function Nested Parameter Definitions

(And I don't mean nested function definitions).

Whilst reading PEP3107 on what's coming this year in Python 3000 I came across this section where it mentions nested parameters in function definitions.
I could not emember this feature so googled a bit, and still could not find it.
It was time to suck-it-and-see, so using Python2.5 I did:


>>> def x ((p0, p1), p2):
... return p0,p1,p2
...
>>> x(('Does', 'this'), 'work')
('Does', 'this', 'work')
>>>

My current skunk-works project extracts data from VHDL source files as a list of nested tuples. I use each outer tuple as a record but unpack the record manually at each function call. If I used the above then the function parameter definition would reflect the record structure.

On closer inspection of the Python Function definition grammar, I find that nested parameters are represented by the sublist token.

Neat!

- Paddy.

2 comments:

  1. Yesterday during PyCon, Brett Cannon asked how many people actually use the nested-parameter feature. Very few hands went up. He asked how many people would like to see it removed, since it makes for such a lot of special-case code in the CPython implementation. ("Special cases aren't special enough to break the rules.") Many hands went up.

    Given yesterday's reactions at PyCon, don't expect this feature to stick around: I expect it will be gone by Python 3.0.

    ReplyDelete
  2. Hi Robin.
    Did Brett ask how many people know the feature is there?
    I had a lot of trouble tracking it down.
    I think it would be better used if an example were added to the tutorial.

    ReplyDelete