Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 7: Style conventions for functions
Functions style guide
While we are discussing functions, let us check our favourite PEP 8 to see what it has to recommend for us about functions.
Naming functions
You should name functions like how you would name variables, i.e. lowercase_with_underscores()
.
I also encourage you to name your functions with actions/verbs, e.g. compute_accuracy()
, repeat()
, package_dataset()
, is_good()
, has_attribute()
. It just makes your code more self-explanatory and easier to understand.
No spaces before the parenthesis
Do not leave spaces between the function name and the ()
. It makes it hard to read. You might think that do_something
is a variable if you separate the ()
. I am strict about this one for our course!
# Good!
def do_something(x):
print(x)
do_something(5)
# NO! NO! NO!
def do_something (x):
print (x)
do_something (5)
No spaces around =
for default arguments/keyword arguments
PEP 8 recommends that you do not put spaces around default arguments in your function definition, or keyword arguments in your function calls.
# Recommended
def generate(real, imag=0.0):
return do_magic(r=real, i=imag)
# Not recommended
def generate(real, imag = 0.0):
return do_magic(r = real, i = imag)
Blank lines
Surround top-level function definitions with two blank lines.
def do_something():
print("Do something")
def do_more():
print("Do more")
def do_even_more():
print("Do even more")