2
import re
import string                                                                     

def buildRule((pattern, search, replace)):                                        
    return lambda word: re.search(pattern, word) and re.sub(search, replace, word) 1

def plural(noun, language='en'):                             2
    lines = file('rules.%s' % language).readlines()          3
    patterns = map(string.split, lines)                      4
    rules = map(buildRule, patterns)                         5
    for rule in rules:                                      
        result = rule(noun)                                  6
        if result: return result   

From : http://www.diveintopython.net/dynamic_functions/stage5.html

The above code works as expected. But buildRule expects tuple but is passed a list in line annotated as 5, above.

Does python does the conversion automatically? If yes, then what is the general rule?

I searched the web, but couldn't get anything useful.

q126y
  • 1,589
  • 4
  • 18
  • 50
  • Yes, Python does the conversion automatically; it's effectively a multi-value assignment, see e.g. http://stackoverflow.com/a/29676756/3001761. Note that this syntax is [no longer valid in 3.x](https://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax). – jonrsharpe Mar 06 '16 at 16:16
  • 1
    BTW, The author also has a book online for Python 3 at [diveintopython3.net](http://www.diveintopython3.net/). – Antti Haapala -- Слава Україні Mar 06 '16 at 16:24
  • @AnttiHaapala Yeah, I realized that after I was more than halfway into the old book. I decided to finish the one I started, because the new book seemed to be structured entirely differently, so I would have had to start the new one from the beginning. – q126y Mar 06 '16 at 16:28

2 Answers2

2

This is called tuple parameter unpacking. Despite its name, it works with any kind of iterable having exactly that many elements.

Tuple parameter unpacking was removed from Python in version 3.0. Reasons for deprecation were discussed in PEP 3113.

It is preferable that you do not use this syntax even in Python 2 any more.


Actually in this case it is not even that useful; buildRule could be defined as

def buildRule(pattern, search, replace):                                        
    return lambda word: re.search(pattern, word) and re.sub(search, replace, word) 1

if line 5 was replaced with

rules = itertools.starmap(buildRule, patterns)
1

You can also convert a list into a tuple. See the following example.

list_array = [1, 2, 3]
tuple_array = tuple(list_array)
Hassan Mehmood
  • 1,414
  • 1
  • 14
  • 22