Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to only import module if necessary and only once

Tags:

python

import

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.

1 Answers

If a module is already loaded then it won't be loaded again. you will just get a reference to it. If you don't plan to use this class locally and just want to satisfy the typehinter then you can do the following

#imports
#import whatever you need localy
from typing import TYPE_CHECKING

if TYPE_CHECKING: # False at runtime
    from matplotlib import pyplot as plt
like image 174
TheLazyScripter Avatar answered Sep 16 '25 22:09

TheLazyScripter