home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 100 / CD-ROM 100.iso / aplic / oo1_1 / f_0396 / python-core-2.2.2 / lib / warnings.py < prev    next >
Encoding:
Python Source  |  2003-07-04  |  8.1 KB  |  259 lines

  1. """Python part of the warnings subsystem."""
  2.  
  3. import sys, re, types
  4.  
  5. __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
  6.            "resetwarnings"]
  7.  
  8. defaultaction = "default"
  9. filters = []
  10. onceregistry = {}
  11.  
  12. def warn(message, category=None, stacklevel=1):
  13.     """Issue a warning, or maybe ignore it or raise an exception."""
  14.     # Check category argument
  15.     if category is None:
  16.         category = UserWarning
  17.     assert issubclass(category, Warning)
  18.     # Get context information
  19.     try:
  20.         caller = sys._getframe(stacklevel)
  21.     except ValueError:
  22.         globals = sys.__dict__
  23.         lineno = 1
  24.     else:
  25.         globals = caller.f_globals
  26.         lineno = caller.f_lineno
  27.     if globals.has_key('__name__'):
  28.         module = globals['__name__']
  29.     else:
  30.         module = "<string>"
  31.     filename = globals.get('__file__')
  32.     if filename:
  33.         fnl = filename.lower()
  34.         if fnl.endswith(".pyc") or fnl.endswith(".pyo"):
  35.             filename = filename[:-1]
  36.     else:
  37.         if module == "__main__":
  38.             filename = sys.argv[0]
  39.         if not filename:
  40.             filename = module
  41.     registry = globals.setdefault("__warningregistry__", {})
  42.     warn_explicit(message, category, filename, lineno, module, registry)
  43.  
  44. def warn_explicit(message, category, filename, lineno,
  45.                   module=None, registry=None):
  46.     if module is None:
  47.         module = filename
  48.         if module[-3:].lower() == ".py":
  49.             module = module[:-3] # XXX What about leading pathname?
  50.     if registry is None:
  51.         registry = {}
  52.     key = (message, category, lineno)
  53.     # Quick test for common case
  54.     if registry.get(key):
  55.         return
  56.     # Search the filters
  57.     for item in filters:
  58.         action, msg, cat, mod, ln = item
  59.         if (msg.match(message) and
  60.             issubclass(category, cat) and
  61.             mod.match(module) and
  62.             (ln == 0 or lineno == ln)):
  63.             break
  64.     else:
  65.         action = defaultaction
  66.     # Early exit actions
  67.     if action == "ignore":
  68.         registry[key] = 1
  69.         return
  70.     if action == "error":
  71.         raise category(message)
  72.     # Other actions
  73.     if action == "once":
  74.         registry[key] = 1
  75.         oncekey = (message, category)
  76.         if onceregistry.get(oncekey):
  77.             return
  78.         onceregistry[oncekey] = 1
  79.     elif action == "always":
  80.         pass
  81.     elif action == "module":
  82.         registry[key] = 1
  83.         altkey = (message, category, 0)
  84.         if registry.get(altkey):
  85.             return
  86.         registry[altkey] = 1
  87.     elif action == "default":
  88.         registry[key] = 1
  89.     else:
  90.         # Unrecognized actions are errors
  91.         raise RuntimeError(
  92.               "Unrecognized action (%s) in warnings.filters:\n %s" %
  93.               (`action`, str(item)))
  94.     # Print message and context
  95.     showwarning(message, category, filename, lineno)
  96.  
  97. def showwarning(message, category, filename, lineno, file=None):
  98.     """Hook to write a warning to a file; replace if you like."""
  99.     if file is None:
  100.         file = sys.stderr
  101.     try:
  102.         file.write(formatwarning(message, category, filename, lineno))
  103.     except IOError:
  104.         pass # the file (probably stderr) is invalid - this warning gets lost.
  105.  
  106. def formatwarning(message, category, filename, lineno):
  107.     """Function to format a warning the standard way."""
  108.     import linecache
  109.     s =  "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
  110.     line = linecache.getline(filename, lineno).strip()
  111.     if line:
  112.         s = s + "  " + line + "\n"
  113.     return s
  114.  
  115. def filterwarnings(action, message="", category=Warning, module="", lineno=0,
  116.                    append=0):
  117.     """Insert an entry into the list of warnings filters (at the front).
  118.  
  119.     Use assertions to check that all arguments have the right type."""
  120.     assert action in ("error", "ignore", "always", "default", "module",
  121.                       "once"), "invalid action: %s" % `action`
  122.     assert isinstance(message, types.StringType), "message must be a string"
  123.     assert isinstance(category, types.ClassType), "category must be a class"
  124.     assert issubclass(category, Warning), "category must be a Warning subclass"
  125.     assert type(module) is types.StringType, "module must be a string"
  126.     assert type(lineno) is types.IntType and lineno >= 0, \
  127.            "lineno must be an int >= 0"
  128.     item = (action, re.compile(message, re.I), category,
  129.             re.compile(module), lineno)
  130.     if append:
  131.         filters.append(item)
  132.     else:
  133.         filters.insert(0, item)
  134.  
  135. def resetwarnings():
  136.     """Clear the list of warning filters, so that no filters are active."""
  137.     filters[:] = []
  138.  
  139. class _OptionError(Exception):
  140.     """Exception used by option processing helpers."""
  141.     pass
  142.  
  143. # Helper to process -W options passed via sys.warnoptions
  144. def _processoptions(args):
  145.     for arg in args:
  146.         try:
  147.             _setoption(arg)
  148.         except _OptionError, msg:
  149.             print >>sys.stderr, "Invalid -W option ignored:", msg
  150.  
  151. # Helper for _processoptions()
  152. def _setoption(arg):
  153.     parts = arg.split(':')
  154.     if len(parts) > 5:
  155.         raise _OptionError("too many fields (max 5): %s" % `arg`)
  156.     while len(parts) < 5:
  157.         parts.append('')
  158.     action, message, category, module, lineno = [s.strip()
  159.                                                  for s in parts]
  160.     action = _getaction(action)
  161.     message = re.escape(message)
  162.     category = _getcategory(category)
  163.     module = re.escape(module)
  164.     if module:
  165.         module = module + '$'
  166.     if lineno:
  167.         try:
  168.             lineno = int(lineno)
  169.             if lineno < 0:
  170.                 raise ValueError
  171.         except (ValueError, OverflowError):
  172.             raise _OptionError("invalid lineno %s" % `lineno`)
  173.     else:
  174.         lineno = 0
  175.     filterwarnings(action, message, category, module, lineno)
  176.  
  177. # Helper for _setoption()
  178. def _getaction(action):
  179.     if not action:
  180.         return "default"
  181.     if action == "all": return "always" # Alias
  182.     for a in ['default', 'always', 'ignore', 'module', 'once', 'error']:
  183.         if a.startswith(action):
  184.             return a
  185.     raise _OptionError("invalid action: %s" % `action`)
  186.  
  187. # Helper for _setoption()
  188. def _getcategory(category):
  189.     if not category:
  190.         return Warning
  191.     if re.match("^[a-zA-Z0-9_]+$", category):
  192.         try:
  193.             cat = eval(category)
  194.         except NameError:
  195.             raise _OptionError("unknown warning category: %s" % `category`)
  196.     else:
  197.         i = category.rfind(".")
  198.         module = category[:i]
  199.         klass = category[i+1:]
  200.         try:
  201.             m = __import__(module, None, None, [klass])
  202.         except ImportError:
  203.             raise _OptionError("invalid module name: %s" % `module`)
  204.         try:
  205.             cat = getattr(m, klass)
  206.         except AttributeError:
  207.             raise _OptionError("unknown warning category: %s" % `category`)
  208.     if (not isinstance(cat, types.ClassType) or
  209.         not issubclass(cat, Warning)):
  210.         raise _OptionError("invalid warning category: %s" % `category`)
  211.     return cat
  212.  
  213. # Self-test
  214. def _test():
  215.     import getopt
  216.     testoptions = []
  217.     try:
  218.         opts, args = getopt.getopt(sys.argv[1:], "W:")
  219.     except getopt.error, msg:
  220.         print >>sys.stderr, msg
  221.         return
  222.     for o, a in opts:
  223.         testoptions.append(a)
  224.     try:
  225.         _processoptions(testoptions)
  226.     except _OptionError, msg:
  227.         print >>sys.stderr, msg
  228.         return
  229.     for item in filters: print item
  230.     hello = "hello world"
  231.     warn(hello); warn(hello); warn(hello); warn(hello)
  232.     warn(hello, UserWarning)
  233.     warn(hello, DeprecationWarning)
  234.     for i in range(3):
  235.         warn(hello)
  236.     filterwarnings("error", "", Warning, "", 0)
  237.     try:
  238.         warn(hello)
  239.     except Exception, msg:
  240.         print "Caught", msg.__class__.__name__ + ":", msg
  241.     else:
  242.         print "No exception"
  243.     resetwarnings()
  244.     try:
  245.         filterwarnings("booh", "", Warning, "", 0)
  246.     except Exception, msg:
  247.         print "Caught", msg.__class__.__name__ + ":", msg
  248.     else:
  249.         print "No exception"
  250.  
  251. # Module initialization
  252. if __name__ == "__main__":
  253.     import __main__
  254.     sys.modules['warnings'] = __main__
  255.     _test()
  256. else:
  257.     _processoptions(sys.warnoptions)
  258.     filterwarnings("ignore", category=OverflowWarning, append=1)
  259.