Change program flow based on available libraries

I am developing a Python model that will support graphical rendering if the correct modules are installed. I would like the source code to be the same, if possible, IE, if the graphic modeling model cannot load, the graphic display will be ignored from the menu logic.

How can i do this?

+4
source share
3 answers

Try to import and set the flag if failed. Then use the flag to determine whether to offer graphical 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) 
+7
source

Yes. You can wrap the import statement in a try - except block. It is commonly used for backward compatibility. For example, importing a return module as the required module. Thus, the rest of the code may not pay attention to which module is actually used.

+1
source

Instead of the flag suggested by @Raymond Hettinger , you can set None actual name, which provides additional features:

 try: import Tkinter except ImportError: display_with_gui = None else: def display_with_gui(): # use Tkinter here pass result = somecalc() if display_with_gui: display_with_gui(result) else: display_as_text(result) 
0
source

All Articles