<< Back to PYTHON
Python Def Methods and Arguments (callable)Use def and callable. See syntax and use tuple and dictionary arguments.
Def. Statements may be top-level. They may come, one after another, in a file. But it is possible to structure logic into methods. This requires the def-keyword.Built-ins
Code reuse. With methods, structured units, we reuse code. Complex logic only needs to be conceived, and written, once. This makes programming easier.
A method. We use def for "dividesafe." This method receives 2 arguments. And in its body, it checks the argument "b" against zero. It returns -1 if the division would cause an error.
However: The method returns the result of the division expression in every other case.
Note: This method receives arguments and returns explicit values. It is possible for a def-method in Python to return no value.
Python program that uses def
def dividesafe(a, b):
# Handle zero denominator.
if b == 0:
return a / b
# Use method.
Pass. It is possible to create an empty method, one with no return value. In methods that return no value, a return statement is not required. In this case we can use a pass statement.pass
Python program that uses pass statement
# This method does nothing.
# Call empty method.
Default. Method arguments can optionally have default values. These defaults are used when no argument is passed to the method. Here, I show a method that has two default-valued arguments.
Width: This is set to 10 when no first argument or named argument is passed to the computesize method.
Height: This is by default set to 2. We can specify just the height using a named argument, as in the third computesize call.
Python program that uses default arguments
def computesize(width=10, height=2):
return width * height
print(computesize()) # 10, 2: defaults used.
print(computesize(5)) # 5, 2: default height.
print(computesize(height=3)) # 10, 3: default width.
One line. We can specify small methods on one line. For short methods, like ones that call other methods (such as print) this syntax is convenient.
Python program that uses one-line def
# Print uppercased form of the string.
def printupper(s): print(s.upper())
In recursion, a method calls itself. This helps solve complex problems. This next program solves no problems. Instead it demonstrates recursion. It ceases once its argument exceeds 10.If
Note: With recursion, we solve search problems. For example, we can determine all possible ways to count change.Recursion
Note 2: If a recursive method calls itself in only one spot, it can be rewritten to instead use iteration.While
Python program that uses recursion
# Stop recursion if depth exceeds 10.
if depth > 10:
# Call itself.
recursive(depth + 1)
Tuple argument. A method in Python can receive any number of arguments stored in a tuple. This requires the single-star syntax. A formal parameter of name *t can be used as a tuple.
Tip: The tuple in this program, of identifier t, can be used in the same way as any tuple.
Python program that receives tuple argument
# Print tuple.
# Loop over tuple items.
for item in t:
# Pass parameters.
display("San Francisco", "Los Angeles", "Sacramento")
display(2, 0, 1, 4)
('San Francisco', 'Los Angeles', 'Sacramento')
(2, 0, 1, 4)
Dictionary argument. Some parameter types have special syntax. A method can receive a dictionary of keys and values. This is specified with two stars before the parameter name.
And: In the method body, we use that parameter as a dictionary. It uses standard dictionary syntax.Dictionary
Tip: The dictionary parameter, specified with this syntax, comes last in the formal parameter list.
Python program that receives dictionary argument
# Loop over dictionary.
for key in values:
print(key, "=", values[key])
# Pass named parameters.
display(first = "Sigmund", last = "Freud", year = 1899)
display(one = 1, two = 2)
year = 1899
last = Freud
first = Sigmund
two = 2
one = 1
Callable. This built-in is not often useful, but I include it for completeness. We can tell if an object (like an integer or lambda) can be called with it.
Python program that uses callable
method = lambda n: n == 2
# A method is callable.
number = 8
# An integer is not callable.
if not callable(number):
Benchmark, inline methods. There is a cost to calling a method. We can reduce this by inlining or combining methods. This can be done by pasting several method bodies together.
Version 1: In this version of the code, method1 returns the results of three sub-methods. The methods are separate in the source code.
Version 2: Method1b directly does the computations. It contains the same logic as version 1.
Result: Inlining can make code harder to read (or, sometimes, easier to read). It reduces method call overhead.
Python program that times methods, inlined computations
# Method that calls other methods.
return method2(v) + method3(v) + method4(v)
return v + 2
return v + 3
return v + 4
# Method with all computations inlined.
return v + 2 + v + 3 + v + 4
# Test them.
# Version 1: non-inlined methods.
i = 0
x = 0
while i < 1000000:
x = method1(5)
i += 1
# Version 2: inlined methods.
i = 0
while i < 1000000:
x = method1b(5)
i += 1
1405711522.499755 method1 = 0.989 s
1405711523.037786 method1b = 0.538 s
Notes, return. We can do more than just return 1 number in Python. We can return a tuple, which contains more than 1 value. Or we can return None (like a void method).Return
Lambda. Often a method has a single statement. The lambda expression syntax, with the keyword "lambda," is helpful here. It makes programs easier to write and shorter.
Caution: For complex methods, or ones that are called in many places, a def-method is often better than a lambda expression.Lambda
Timeit. Statements and methods can be benchmarked. You can use simple calls to time(), or the more complex timeit module. Micro-benchmarks tend to waste a lot of time.Timeit
A summary. Structured programming was introduced in the 1960s. In this new style, software was divided into functions. These functions are independent but can call other functions.
With def, a function syntax form, we add further levels of structure to our programs. This yields programs that are clearer, smaller and often faster than unstructured designs.