Why the code below throws undefined name sheetname?
def PlotChart(charttype = 'line', sheetname = 'CA', values = '='+sheetname+'!$M$1:$M$400'):
Any ways I can fix this?
Why the code below throws undefined name sheetname?
def PlotChart(charttype = 'line', sheetname = 'CA', values = '='+sheetname+'!$M$1:$M$400'):
Any ways I can fix this?
Default parameter values are evaluated when the function is defined, thus you can not access another parameter value that will only be known when the function is called.
I'd suggest using None
as the default and then setting the proper default value afterwards.
def PlotChart(charttype='line', sheetname='CA', values=None):
if values is None:
values = '=' + sheetname + '!$M$1:$M$400'
...
Or slightly shorter, using or
to get a "default" value (this will also replace empty ""
, though)
values = values or ('=' + sheetname + '!$M$1:$M$400')
If sheetname
always has to be part of values
, you could also expect a format string, and then format it with the actual value for sheetname
after the function has been called:
def PlotChart(charttype='line', sheetname='CA', values='={}!$M$1:$M$400'):
values = values.format(sheetname)
...
If there will always be sheetname in values
You should perform the addition inside the function:
def PlotChart(charttype = 'line', sheetname = 'CA', values = '!$M$1:$M$400'):
values = '=' + sheetname + values
If you want user to change completely values:
You should call the function with what you want
def PlotChart(values, charttype = 'line', sheetname = 'CA'):
...
PlotChart(charttype = 'line', sheetname = 'CA', values = '=' + sheetname + values)
If you want both:
tobias_k answers is the best: use None
def PlotChart(charttype='line', sheetname='CA', values=None):
if values is None:
values = '='+sheetname+'!$M$1:$M$400'):
...