0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
G Tsirigos
  • 83
  • 9

2 Answers2

4

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)
    ...
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • The last one is very fragile; it will break if the caller provides an incompatible format string. I don't seen any reason *not* to use the first suggestion that explicitly checks for a `None` value. – chepner Jun 08 '18 at 13:31
  • @chepner Yes, it's fragile, and the format should probably be explained in the docstring. One benefit might be that the default is more obvious than when using `None` and checking it somewhere (preferrably in the first line) in the code. (On the other hand, when using `None` one could also explain the _actual_ default in the docstring.) – tobias_k Jun 08 '18 at 13:46
1

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'):
    ...
Emmanuel-Lin
  • 1,848
  • 1
  • 16
  • 31