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 -1 # Divide. return a / b # Use method. print(dividesafe(10, 5)) print(dividesafe(10, 0)) Output 2.0 -1

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 def waste_of_time(): # This method does nothing. pass # Call empty method. waste_of_time()

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. Output 20 10 30

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()) printupper("hello") printupper("world") Output HELLO WORLD

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.


Note 2: If a recursive method calls itself in only one spot, it can be rewritten to instead use iteration.

Python program that uses recursion def recursive(depth): # Stop recursion if depth exceeds 10. if depth > 10: return print(depth) # Call itself. recursive(depth + 1) # Begin. recursive(5) Output 5 6 7 8 9 10

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 def display(*t): # Print tuple. print(t) # Loop over tuple items. for item in t: print(item) # Pass parameters. display("San Francisco", "Los Angeles", "Sacramento") display(2, 0, 1, 4) Output ('San Francisco', 'Los Angeles', 'Sacramento') San Francisco Los Angeles Sacramento (2, 0, 1, 4) 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.


Tip: The dictionary parameter, specified with this syntax, comes last in the formal parameter list.

Python program that receives dictionary argument def display(**values): # Loop over dictionary. for key in values: print(key, "=", values[key]) # Newline. print() # Pass named parameters. display(first = "Sigmund", last = "Freud", year = 1899) display(one = 1, two = 2) Output 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. if callable(method): print(True) number = 8 # An integer is not callable. if not callable(number): print(False) Output True False

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 import time # Method that calls other methods. def method1(v): return method2(v) + method3(v) + method4(v) def method2(v): return v + 2 def method3(v): return v + 3 def method4(v): return v + 4 # Method with all computations inlined. def method1b(v): return v + 2 + v + 3 + v + 4 # Test them. print(method1(5)) print(method1b(5)) print(time.time()) # Version 1: non-inlined methods. i = 0 x = 0 while i < 1000000: x = method1(5) i += 1 print(time.time()) # Version 2: inlined methods. i = 0 while i < 1000000: x = method1b(5) i += 1 print(time.time()) Output 24 24 1405711521.510698 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.


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.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to