Skip to content
Search

Python:Function

lastmod 2020-10-17created 2015-04-149 edits

Python functools package.

Built-in Functions

filter

filter(function, literable)

Feeds the elements of the iterable given as the second argument one by one into the function given as the first argument, and returns only those whose return value is true.

reduce

WARNING

Removed from the built-in functions as of python3. It is available from the functools package instead.

reduce(function, iterable[, initializer])

Example:

from functools import reduce
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
# = ((((1+2)+3)+4)+5)

args and kwargs

*args is used when you don't know how many parameters will be received. They are passed as a tuple. **kwargs lets you send parameter names along with the values. They are passed as a dictionary.

def print_param3(*args, **kwargs):
    print args
    print kwargs

print_param3('a', 'b')
#('a', 'b')
#{}

print_param3(third = 'c', fourth = 'd')
#()
#{'fourth': 'd', 'third': 'c'}

print_param3('a', 'b', third = 'c', fourth = 'd')
#('a', 'b')
#{'fourth': 'd', 'third': 'c'}

Passing variable arguments as a Tuple

def test_var_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "another arg:", arg

test_var_args(1, "two", 3)

Passing variable arguments as a Dictionary

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

Using variable arguments and dictionaries together

Order of *arg, **kwargs, and formal arguments (format args):

def some_func(fargs, *args, **kwargs):
    # ...
    pass

Variable argument By-pass

To pass variable arguments on again, write them in the arguments with * or **.

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

See also

Favorite site

Variable argument

author Zer0 sitemap