user9413641
user9413641

Reputation:

how to only import module if necessary and only once

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":

Upvotes: 4

Views: 7859

Answers (3)

Anthony
Anthony

Reputation: 2050

TLDR; Python does so for you already, for free.

Python import machinery imports module only once, even if it was imported multiple times. Even from different files (docs).

The most pythonic way to import something is to do so at the beginning of file. Unless you have special needs, like import different modules depending on some condition, eg. platform (windows, linux).

Upvotes: -1

araldhafeeri
araldhafeeri

Reputation: 187

Optional import in Python:

try: 
    import something
    import_something = True
except ImportError:
    import something_else
    import_something_else = True

Conditional import in Python:

if condition: 
    import something
    # something library related code
elif condition: 
    # code without library 

import related to one function:

def foo():
   import some_library_to_use_only_inside_foo

Upvotes: 1

TheLazyScripter
TheLazyScripter

Reputation: 2665

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

Upvotes: 4

Related Questions