Search code examples
pythonmoduleglobal-variables

Convention for global parameter in python module


I have a module with several plotting functions and I want to have two color themes, one with light color and the other with dark color.

I say I have two methods:

def plot_function_1(color_dark='#212121'):
    ...

def plot_function_2(color_dark='#212121'):
    ...

That feels kind of redundant. What is the most pythonic way to deal with this? Would I define a variable in the module COLOR_DARK = '#212121' and then call:

def plot_function_1(color_dark=COLOR_DARK):
    ...

Solution

  • Create a dict of colors and pass the one required.

    color_dict = {'COLOR_DARK': '#212121', 'COLOR_LIGHT': '#121212'}
    
    def plot_function_1(color):
        print(color)
    
    
    plot_function_1(color_dict['COLOR_DARK'])
    

    OUTPUT:

    #212121
    

    Another approach (using enum):

    from enum import Enum
    
    class Color(Enum):
        DARK_COLOR = 200
        LIGHT_COLOR = 400
        DARKER_COLOR = 500
        LIGHTER_COLOR = 222
    
        print(Color.DARK_COLOR.name)
        print(Color.DARK_COLOR.value)
    

    OUTPUT:

    DARK_COLOR
    200
    

    Similarly:

    def plot_function_1(color):
        print(color)
    
    
    plot_function_1(Color.DARK_COLOR.name)    # or use .value if required