'running exec inside a function when calling a module

I'm trying to assign a module's attribute to a variable using exec inside a function. color is a str like: 'jet', 'seismic', 'nipy_spectral', or something else. But didn't work.

#%% 0
#=============================================================>
def my_color(color):
    import matplotlib.colors as mpc
    import numpy as np 
    from matplotlib.pyplot import cm

    n=30
    x = 0.5
    
    col={}
    exec("cmap = cm." + color,col)
    cmap = col["cmap"]
    
    lower = cmap(np.linspace(0, x, n))
    white = np.ones((5,4))
    upper = cmap(np.linspace(1-x, 1, n))
    colors = np.vstack((lower, white, upper))

    tmap = mpc.LinearSegmentedColormap.from_list('map_white', colors)
    
    return tmap

#=============================================================> 

But got that error :

my_color(color)

Traceback (most recent call last):

  File "/tmp/ipykernel_26467/1213546374.py", line 1, in <module>
    my_color(color)

  File "/tmp/ipykernel_26467/827626903.py", line 11, in my_color
    exec("cmap = cm." + color,col)

  File "<string>", line 1, in <module>

NameError: name 'cm' is not defined

Can someone help !?

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source