Porably importing modules

Graham Ashton graz at mindless.com
Thu Aug 23 12:17:15 EDT 2001


I'm sure there's a more idiomatic way to trap the failure to import a
module than my attempt. Whilst making sure one of my apps runs on Windows
as well as Unix I came up with the following code (re-typed and untested):

  # catch failure to import and let it pass
  try:
      import syslog
  except ImportError, e:
      print "can't import syslog: %s" % e

  # [ snip loads of stuff ]

  # make sure syslog is imported before trying to use it
  if "syslog" in dir():
      syslog.openlog(...)
  else:
      print "sorry, no syslog support"

Am I re-inventing a perfectly round wheel? Is there a cleaner way?

Thanks.

--
Graham

P.S. Does anybody know of any Python portability guidelines?



More information about the Python-list mailing list