pythonmatplotlibpython-typing

Type hint for a matplotlib color?


I'm type-hinting functions in Python, and not sure what type a matplotlib color should be. I have a function like this:

def plot_my_thing(data: np.ndarray, color: ???):
    # function def here

What should the type be in ???, when it is meant to be a matplotlib color that you can feed into plt.plot() for the type hint? Right now I'm planning to just use Any.

I've searched and not found an answer. There are some discussions at GitHub about it:

https://github.com/matplotlib/matplotlib/issues/21505

But that seems like a package-specific problem, though I may not be understanding it.


Solution

  • Matplotlib introduced type hints in 3.8.0. Now, you can use matplotlib.typing.ColorType which is just an alias for all valid matplotlib colors.

    For more information, see the matplotlib typing api reference.