DL Neil writes: > On 18/04/19 8:44 AM, Grant Edwards wrote: > > 2. When the program can still do something useful (if perhaps > > feature-limited) without the imported module by substituting > > something else in its place. > > Any (publishable) examples?
One of the targets my RSS fetching program supports is Plucker on PalmOS, which used to be how I read RSS feeds back in the day (nowadays I use simplified HTML on Android). Plucker on Palm had problems with accented characters, so I added a little module called ununicode to translate strings to plain ASCII (so á would become a). For most target platforms, it was a nonissue. try: import ununicode has_ununicode = True except ImportError as e: has_ununicode = False def output_encode(s, encoding): if encoding == 'ascii' and has_ununicode: return ununicode.toascii(s, in_encoding=encoding) else: return s The program still worked fine if the module wasn't there, it just wrote accented characters because it couldn't simplify them. And yes, it could have tested "if 'ununicode' in sys.modules" instead of setting a variable; I didn't know about that at the time. > but... what of the third inherent assumption: that the user(s) will be able > to handle the situation (discussed in another msg 'here')? One example: there are a gazillion whois modules, and when I run my domaincheck program on a machine where I haven't yet installed whois, it's helpful to have a reminder of which one I should install. (Of course, if you have one of the other whois modules installed, the program will fail somewhere else.) try: import whois # python-whois from pypi, not whois from pypi or python-whois from debian # https://bitbucket.org/richardpenman/pywhois except ImportError: print("Couldn't import whois. Try: pip3 install python-whois") sys.exit(1) The third case has already been mentioned: modules that change name but don't change their APIs much. # Tkinter changed capitalization from Python 2 to Python 3. try: import tkinter except ModuleNotFoundError: import Tkinter as tkinter I thought I had examples for gtk and qt -- GUI libraries change their import syntax a lot -- but I can't find them. ...Akkana -- https://mail.python.org/mailman/listinfo/python-list