Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

python - Can I make the import package only check for the package if that class or function is called?

I only want to import a package when the function using that package is called. Is there any way I can do this

class metarmap:
import metar_map as mm
import neopixel
import board


def __init__(self, airport):
    pass

def __repr__(self):
    return str('Hey Dont import noepixel or board til I call the .metarmap method!')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may not know this but import statements are still statements, this means you could do something like this:

<code here>
if <condition>:
    import <package>

and it'd be very valid


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...