I want to teach students about default function arguments.
I have a bad habit of cooking-up contrived examples.
To prove that I am not a student cheating on their homework, I shall provide you with the following code. I really can write an example of a function without default arguments on my own, it is simply too contrived:
class SandwhichMaker:
FISH = """
/"*._ _
.-*'` `*-.._.-'/
< * )) , (
`*-._`._(__.--*"`.\
"""
@classmethod
def publicly_make_sandwhich(klass, bread, veggie, meat = "fish", sauce = None):
if (sauce == None):
sauce = klass.meat_to_sauce(meat)
bread = str(bread)
veggie = str(veggie)
meat = str(meat).lower()
if meat == "fish":
meat = SandwhichMaker.FISH
sandwhich = klass.privatly_make_sandwhich(bread, veggie, meat, sauce)
return sandwhich
@classmethod
def meat_to_sauce(cls, meat):
if meat.lower() == "fish":
return "tartar sauce"
@classmethod
def privatly_make_sandwhich(cls, bread, veggie, meat, sauce):
"""
PRECONDITION: all input parameters are strings
"""
seperator = "\n" + 40 * "-" + "\n"
sandwhich = seperator.join([
"\n\n",
bread,
veggie,
meat,
sauce,
bread
])
return sandwhich
sw = SandwhichMaker()
sandwhich = sw.publicly_make_sandwhich("whole wheat", "cucumber", "fish")
print(sandwhich)
Console output:
----------------------------------------
whole wheat
----------------------------------------
cucumber
----------------------------------------
/"*._ _
.-*'` `*-.._.-'/
< * )) , (
`*-._`._(__.--*"`.\
----------------------------------------
tartar sauce
----------------------------------------
whole wheat
So, my example function with default arguments is as follows:
publicly_make_sandwhich(klass, bread, veggie, meat = "fish", sauce = None):
The default meat
is "fish"
I really want students to see how default arguments can be useful.
I thought about downloading a few open source code repositories.
I could then search all text-files for a regular expression (regex) to find functions having default arguments.
\(\s*\w*\s*\w+\s*=[^),][^)]*\)
- Exactly one left parenthesis ...
[1, 1]
of(
- Zero or more of any white-space character (
[0, +inf]
of\s
)- optional data-type such as
float
orint
. zero or more letters, numbers or underscores.[1, +inf]
of[a-zA-Z0-9_]
- zero or more white-space characters
- one or more letters, numbers or underscores.
- zero or more white-space chars
- exactly one equals sign
- exactly one character except right-paren or comma
- zero or more character other than right-paren
- exactly one right-parenthesis
It would be easier just to ask a human being for a good example.
debug=false
$\endgroup$