Default values of parameters can be defined in the function definition.
Example 13.1. Default values of parameters
Say that you have a function that checks whether a sequence is correct with respect to a given alphabet.
def checkseq(seq, alphabet):
for c in seq:
if c not in alphabet:
return False
return True
To use the DNA alphabet as default value for the alphabet parameters, the checkseq function can be redefined as follow:
def checkseq(seq, alphabet="actg"):
for c in seq:
if c not in alphabet:
return False
return True
So, you can now call it this way:
>>> result = checkseq("atgcgtgatgdtgragt")
False
>>> myseq = "agcucgaua"
>>> result = checkseq(myseq, "acgu")
True
Default values are referenced when the function is defined.
alphabet = "actg"
def checkseq(seq, alphabet=alphabet):
for c in seq:
if c not in alphabet:
return False
return True
If you change the global alphabet
variable later, this will not be taken into account, except if
the default value is a mutable type of course (e.g: list or dictionary).
alphabet = "actg"
def checkseq(seq, alphabet=alphabet):
for c in seq:
if c not in alphabet:
return False
return True
alphabet = "acug"
>>> result = checkseq("atgcgtgatgdtgragt")
True