1
+ [ Contents] ( ../Contents ) \| [ Previous (2.7 Object Model)] ( ../02_Working_with_data/07_Objects ) \| [ Next (3.2 More on Functions)] ( 02_More_functions )
2
+
1
3
# 3.1 Scripting
2
4
3
5
In this part we look more closely at the practice of writing Python
@@ -16,7 +18,7 @@ statement3
16
18
...
17
19
```
18
20
19
- We have been writing scripts to this point.
21
+ We have mostly been writing scripts to this point.
20
22
21
23
### A Problem
22
24
@@ -28,7 +30,7 @@ organized.
28
30
29
31
### Defining Things
30
32
31
- You must always define things before they get used later on in a program .
33
+ Names must always be defined before they get used later.
32
34
33
35
``` python
34
36
def square (x ):
@@ -41,11 +43,12 @@ z = square(b) # Requires `square` and `b` to be defined
41
43
```
42
44
43
45
** The order is important.**
44
- You almost always put the definitions of variables an functions near the beginning .
46
+ You almost always put the definitions of variables and functions near the top .
45
47
46
48
### Defining Functions
47
49
48
50
It is a good idea to put all of the code related to a single * task* all in one place.
51
+ Use a function.
49
52
50
53
``` python
51
54
def read_prices (filename ):
@@ -85,7 +88,7 @@ def foo():
85
88
help (math)
86
89
```
87
90
88
- There are no * special* statements in Python.
91
+ There are no * special* statements in Python (which makes it easy to remember) .
89
92
90
93
### Function Definition
91
94
@@ -106,13 +109,14 @@ def foo(x):
106
109
bar(x)
107
110
```
108
111
109
- Functions must only be defined before they are actually * used* (or called) during program execution.
112
+ Functions must only be defined prior to actually being * used* (or called) during program execution.
110
113
111
114
``` python
112
115
foo(3 ) # foo must be defined already
113
116
```
114
117
115
- Stylistically, it is probably more common to see functions defined in a * bottom-up* fashion.
118
+ Stylistically, it is probably more common to see functions defined in
119
+ a * bottom-up* fashion.
116
120
117
121
### Bottom-up Style
118
122
@@ -137,24 +141,26 @@ def spam(x):
137
141
spam(42 ) # Code that uses the functions appears at the end
138
142
```
139
143
140
- Later functions build upon earlier functions.
144
+ Later functions build upon earlier functions. Again, this is only
145
+ a point of style. The only thing that matters in the above program
146
+ is that the call to ` spam(42) ` go last.
141
147
142
148
### Function Design
143
149
144
150
Ideally, functions should be a * black box* .
145
151
They should only operate on passed inputs and avoid global variables
146
- and mysterious side-effects. Main goals: * Modularity* and * Predictability* .
152
+ and mysterious side-effects. Your main goals: * Modularity* and * Predictability* .
147
153
148
154
### Doc Strings
149
155
150
- A good practice is to include documentations in the form of
151
- doc-strings . Doc-strings are strings written immediately after the
156
+ It's good practice to include documentation in the form of a
157
+ doc-string . Doc-strings are strings written immediately after the
152
158
name of the function. They feed ` help() ` , IDEs and other tools.
153
159
154
160
``` python
155
161
def read_prices (filename ):
156
162
'''
157
- Read prices from a CSV file of name,price
163
+ Read prices from a CSV file of name,price data
158
164
'''
159
165
prices = {}
160
166
with open (filename) as f:
@@ -164,14 +170,19 @@ def read_prices(filename):
164
170
return prices
165
171
```
166
172
173
+ A good practice for doc strings is to write a short one sentence
174
+ summary of what the function does. If more information is needed,
175
+ include a short example of usage along with a more detailed
176
+ description of the arguments.
177
+
167
178
### Type Annotations
168
179
169
- You can also add some optional type annotations to your function definitions.
180
+ You can also add optional type hints to function definitions.
170
181
171
182
``` python
172
183
def read_prices (filename : str ) -> dict :
173
184
'''
174
- Read prices from a CSV file of name,price
185
+ Read prices from a CSV file of name,price data
175
186
'''
176
187
prices = {}
177
188
with open (filename) as f:
@@ -181,13 +192,15 @@ def read_prices(filename: str) -> dict:
181
192
return prices
182
193
```
183
194
184
- These do nothing. It is purely informational.
185
- They may be used by IDEs, code checkers, etc.
195
+ The hints do nothing operationally. They are purely informational.
196
+ However, they may be used by IDEs, code checkers, and other tools
197
+ to do more.
186
198
187
199
## Exercises
188
200
189
- In section 2, you wrote a program called ` report.py ` that printed out a report showing the performance of a stock portfolio.
190
- This program consisted of some functions. For example:
201
+ In section 2, you wrote a program called ` report.py ` that printed out
202
+ a report showing the performance of a stock portfolio. This program
203
+ consisted of some functions. For example:
191
204
192
205
``` python
193
206
# report.py
@@ -215,8 +228,9 @@ def read_portfolio(filename):
215
228
...
216
229
```
217
230
218
- However, there were also portions of the program that just performed a series of scripted calculations.
219
- This code appeared near the end of the program. For example:
231
+ However, there were also portions of the program that just performed a
232
+ series of scripted calculations. This code appeared near the end of
233
+ the program. For example:
220
234
221
235
``` python
222
236
...
@@ -231,7 +245,8 @@ for row in report:
231
245
...
232
246
```
233
247
234
- In this exercise, we’re going take this program and organize it a little more strongly around the use of functions.
248
+ In this exercise, we’re going take this program and organize it a
249
+ little more strongly around the use of functions.
235
250
236
251
### Exercise 3.1: Structuring a program as a collection of functions
237
252
@@ -242,10 +257,12 @@ functions. Specifically:
242
257
* Create a function ` print_report(report) ` that prints out the report.
243
258
* Change the last part of the program so that it is nothing more than a series of function calls and no other computation.
244
259
245
- ### Exercise 3.2: Creating a function for program execution
260
+ ### Exercise 3.2: Creating a top-level function for program execution
246
261
247
- Take the last part of your program and package it into a single function ` portfolio_report(portfolio_filename, prices_filename) ` .
248
- Have the function work so that the following function call creates the report as before:
262
+ Take the last part of your program and package it into a single
263
+ function ` portfolio_report(portfolio_filename, prices_filename) ` .
264
+ Have the function work so that the following function call creates the
265
+ report as before:
249
266
250
267
``` python
251
268
portfolio_report(' Data/portfolio.csv' , ' Data/prices.csv' )
@@ -256,8 +273,9 @@ of function definitions followed by a single function call to
256
273
` portfolio_report() ` at the very end (which executes all of the steps
257
274
involved in the program).
258
275
259
- By turning your program into a single function, it becomes easy to run it on different inputs.
260
- For example, try these statements interactively after running your program:
276
+ By turning your program into a single function, it becomes easy to run
277
+ it on different inputs. For example, try these statements
278
+ interactively after running your program:
261
279
262
280
``` python
263
281
>> > portfolio_report(' Data/portfolio2.csv' , ' Data/prices.csv' )
@@ -272,4 +290,13 @@ For example, try these statements interactively after running your program:
272
290
>> >
273
291
```
274
292
293
+ ### Commentary
294
+
295
+ Python makes it very easy to write relatively unstructured scripting code
296
+ where you just have a file with a sequence of statements in it. In the
297
+ big picture, it's almost always better to utilize functions whenever
298
+ you can. At some point, that script is going to grow and you'll wish
299
+ you had a bit more organization. Also, a little known fact is that Python
300
+ runs a bit faster if you use functions.
301
+
275
302
[ Contents] ( ../Contents ) \| [ Previous (2.7 Object Model)] ( ../02_Working_with_data/07_Objects ) \| [ Next (3.2 More on Functions)] ( 02_More_functions )
0 commit comments