q126y
q126y

Reputation: 1671

passing list to function expecting tuple of same length

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.

Upvotes: 2

Views: 984

Answers (2)

Hassan Mehmood
Hassan Mehmood

Reputation: 1402

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

list_array = [1, 2, 3]
tuple_array = tuple(list_array)

Upvotes: 1

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)

Upvotes: 2

Related Questions