0

I have a plotting module imported by other scripts/jupyter notebooks which has a global variable denoting font size on the axis labels. This variable is used as default for a function setting axis labels:

FONT_SIZE=14
def pltlabel(title='', x='', y='', size=FONT_SIZE):
    """ this function is used by other functions within the same module"""
    plt.title(title, fontsize=size)
    plt.xlabel(x, fontsize=size)
    plt.ylabel(y, fontsize=size)

In some scenarios I want to change this font globally. I've tried creating a function to do so

def change_global_fontsize(s):
    global FONT_SIZE
    FONT_SIZE = s

and calling in the notebook where plotting takes place, but it doesn't really change the value of the global, as I can see when I call my plotting functions.

I do see why this is happening - value of data from a module is essentially unidirectional, and once it's imported it cannot be changed within the module.

What is the best approach for what I'm trying to accomplish?

Brian Barry
  • 439
  • 2
  • 17

1 Answers1

2

The problem is that default function argument values are only evaluated once when the function is defined, not each time it is called. So the right-hand side of size=FONT_SIZE is only evaluated once, and that is used as the default value for size for any future function calls.

You should use FONT_SIZE as the default inside the function so it gets the current value each time. Specifically, set size=None as the default argument, and replace inside the function, eg:

FONT_SIZE=14
def pltlabel(title='', x='', y='', size=None)
    if size is None:
        size = FONT_SIZE
    ...

See "Least Astonishment" and the Mutable Default Argument.

craigb
  • 1,081
  • 1
  • 9