I’m learning Python and wanted to see if anyone could help break down and understand what this function does step by step?
def label(self, index, *args):
"""
Label each axes one at a time
args are of the form <label 1>,...,<label n>
APIPARAM: chxl
"""
self.data['labels'].append(
str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','')
)
return self.parent
It’s a good idea to change the formatting, before trying to understand what it does:
So:
it appends something to
self.data[ 'labels' ]list. We know this becauseappend()is a method of list object.This something is a string such that:
xxx:|yyyxxxis replaced with the value of argumentindexyyyis replaced with all the other arguments converted to strings (map(str,args)) and joined with|character (join(...)) so resulting in something like ‘a|b|None|c‘Nonein the string above is replaced with an empty string and this is appended to the listEDIT:
As @abarnert pointed out it might be good to explain what does
*argsmean and why later on it’s used asargs, so here it goes.*args(which is an asterisk + an arbitrary name) means “any number of anonymous arguments available further inargslist”. One can also use**kwargs– note two asterisk which is used for accepting keyworded arguments, i.e. ones passed to the function in the form offoo = barwherefoois the name of the argument andbaris its value rather than justbar.As said above
argsandkwargsare arbitrary, one could just as well use*potatoesor**potatoesbut usingargsandkwargsis a convention in Python (sometimes people also use**kwinstead of**kwargs, but the meaning is the same – any number of anonymous and any number of keyworded arguments respectively).Both are used if the number of arguments which the function/method should accept is not known beforehand – consider for a example a function which processes names of the party guests, one may not know how many there may be, so defining a following function makes sense:
Then both calls below are valid:
This is also explained in this SO post: https://stackoverflow.com/a/287101/680238