The _ _builtin_ _ Module
This module contains built-in functions that are automatically available in all Python modules. You usually don’t have to import this module; Python does that for you when necessary.
Calling a Function with Arguments from a Tuple or Dictionary
Python allows you to build function argument lists on the fly. Just
put all the arguments in a tuple, and call the built-in
apply function, as illustrated in Example 1-1.
Example 1-1. Using the apply Function
File: builtin-apply-example-1.py
def function(a, b):
print a, b
apply(function, ("whither", "canada?"))
apply(function, (1, 2 + 3))
whither canada?
1 5
To pass keyword arguments to a function, you can use a dictionary as
the third argument to apply, as shown in Example 1-2.
Example 1-2. Using the apply Function to Pass Keyword Arguments
File: builtin-apply-example-2.py
def function(a, b):
print a, b
apply(function, ("crunchy", "frog"))
apply(function, ("crunchy",), {"b": "frog"})
apply(function, (), {"a": "crunchy", "b": "frog"})
crunchy frog
crunchy frog
crunchy frog
One common use for apply is to pass constructor
arguments from a subclass on to the base class, especially if the
constructor takes a lot of arguments. See Example 1-3.
Example 1-3. Using the apply Function to Call Base Class Constructors
File: builtin-apply-example-3.py class Rectangle: def _ _init_ _(self, color="white", width=10, height=10): print "create a", color, self, "sized", width, "x", height class RoundedRectangle(Rectangle): def ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access