[Python] how to only import module if necessary and only once

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class which can be plotted using matplotlib, but it can (and will) also be used without plotting it.

    I would like to only import matplotlib if necessary, ie. if the plot method is called on an instance of the class, but at the same time I would like to only import matplotlib once if at all.

    Currently what I do is:

    class Cheese:
    def plot(self):
    from matplotlib import pyplot as plt
    # *plot some cheese*


    ..but I suppose that this may lead to importing multiple times.

    I can think of lots of ways to accomplish only importing once, but they are not pretty.

    What is a pretty and "pythonic" way of doing this?

    I don't mean for this to be "opinion based", so let me clarify what I mean by "pretty":

    • using the fewest lines of code.
    • most readable
    • most efficient
    • least error-prone etc.

    Continue reading...

Compartilhe esta Página