- Python Shortcuts, Commands, and Packages
- 4.2 Twenty-Two Programming Shortcuts
- 4.3 Running Python from the Command Line
- 4.4 Writing and Using Doc Strings
- 4.5 Importing Packages
- 4.6 A Guided Tour of Python Packages
- 4.7 Functions as First-Class Objects
- 4.8 Variable-Length Argument Lists
- 4.9 Decorators and Function Profilers
- 4.10 Generators
- 4.11 Accessing Command-Line Arguments
- Chapter 4 Summary
- Chapter 4 Questions for Review
- Chapter 4 Suggested Problems
4.7 Functions as First-Class Objects
Another productivity tool—which may be useful in debugging, profiling, and related tasks—is to treat Python functions as first-class objects. That means taking advantage of how you can get information about a function at run time. For example, suppose you’ve defined a function called avg.
def avg(a_list): '''This function finds the average val in a list.''' x = (sum(a_list) / len(a_list)) print('The average is:', x) return x
The name avg is a symbolic name that refers to a function, which in Python lingo is also a callable. There are a number of things you can do with avg, such as verify its type, which is function. Here’s an example:
>>> type(avg) <class 'function'>
We already know that avg names a function, so this is not new information. But one of the interesting things you can do with an object is assign it to a new name. You can also assign a different function altogether to the symbolic name, avg.
def new_func(a_list): return (sum(a_list) / len(a_list)) old_avg = avg avg = new_func
The symbolic name old_avg now refers to the older, and longer, function we defined before. The symbolic name avg now refers to the newer function just defined.
The name old_avg now refers to our first averaging function, and we can call it, just as we used to call avg.
>>> old_avg([4, 6]) The average is 5.0 5.0
The next function shown (which we might loosely term a “metafunction,” although it’s really quite ordinary) prints information about another function—specifically, the function argument passed to it.
def func_info(func): print('Function name:', func._ _name_ _) print('Function documentation:') help(func)
If we run this function on old_avg, which has been assigned to our first averaging function at the beginning of this section, we get this result:
Function name: avg Function documentation: Help on function avg in module _ _main_ _: avg(a_list) This function finds the average val in a list.
We’re currently using the symbolic name old_avg to refer to the first function that was defined in this section. Notice that when we get the function’s name, the information printed uses the name that the function was originally defined with.
All of these operations will become important when we get to the topic of “decorating” in Section 4.9, “Decorators and Function Profilers.”