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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With