[Python] How to add type hints for an optional dependency in Python? [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    In a Python package, matplotlib is used only in one function and hence, is defined as an optional dependency. This function takes an optional ax-argument.

    def my_plot_function(ax=None):

    if ax is None:
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()

    # plot someting...

    return ax


    What is the best way to add type hints without making matplotlib a required dependency? Is this possible with some fake types in case matplotlib is not installed?

    from matplotlib.axes import Axes

    def my_plot_function(ax : None | Axes = None) -> Axes:

    if ax is None:
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()

    # plot someting...

    return ax


    Would

    try:
    from matplotlib.axes import Axes

    except ModuleNotFoundError:

    class Axes:
    pass


    be an option?

    Importing classes just for typing in python? has no selected answers. This question is not about circular imports. It's about types from optional dependencies. Is there any other (newer) way than a type annotation in enclosed quotes like suggested in Importing classes just for typing in python??

    Continue reading...

Compartilhe esta Página