Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Program Flow based on Available Libraries

I am developing a Python model that will support graphing if the correct modules are installed. I would like the source code to be the same if possible, IE, if the graphing model can't load, graphing would be ignored from the menu logic.

How can I accomplish this?

like image 720
Nathan Tornquist Avatar asked Feb 23 '23 15:02

Nathan Tornquist


2 Answers

Attempt an import and set a flag if fails. Then use the flag to determine whether to offer graphic output:

try:
    import Tkinter
    gui_installed = True
except ImportError:
    gui_installed = False


...

result = somecalc()
if gui_installed:
    display_with_gui(result)
else:
    display_as_text(result)
like image 74
Raymond Hettinger Avatar answered Mar 03 '23 00:03

Raymond Hettinger


Yes. You can wrap an import statement in a try-except block. It is commonly used for backwards-compatability cruft. For instance, by importing a fall-back module as the desired module. That way the rest of the code can be oblivious to which module is actually in use.

like image 27
retracile Avatar answered Mar 03 '23 00:03

retracile