home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Inkscape / Inkscape-0.48.2-1-win32.exe / python / Lib / warnings.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-03-27  |  12.7 KB  |  442 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Python part of the warnings subsystem.'''
  5. import linecache
  6. import sys
  7. import types
  8. __all__ = [
  9.     'warn',
  10.     'showwarning',
  11.     'formatwarning',
  12.     'filterwarnings',
  13.     'resetwarnings',
  14.     'catch_warnings']
  15.  
  16. def warnpy3k(message, category = None, stacklevel = 1):
  17.     '''Issue a deprecation warning for Python 3.x related changes.
  18.  
  19.     Warnings are omitted unless Python is started with the -3 option.
  20.     '''
  21.     if sys.py3kwarning:
  22.         if category is None:
  23.             category = DeprecationWarning
  24.         
  25.         warn(message, category, stacklevel + 1)
  26.     
  27.  
  28.  
  29. def _show_warning(message, category, filename, lineno, file = None, line = None):
  30.     '''Hook to write a warning to a file; replace if you like.'''
  31.     if file is None:
  32.         file = sys.stderr
  33.     
  34.     
  35.     try:
  36.         file.write(formatwarning(message, category, filename, lineno, line))
  37.     except IOError:
  38.         pass
  39.  
  40.  
  41. showwarning = _show_warning
  42.  
  43. def formatwarning(message, category, filename, lineno, line = None):
  44.     '''Function to format a warning the standard way.'''
  45.     s = '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)
  46.     line = None if line is None else line
  47.     if line:
  48.         line = line.strip()
  49.         s += '  %s\n' % line
  50.     
  51.     return s
  52.  
  53.  
  54. def filterwarnings(action, message = '', category = Warning, module = '', lineno = 0, append = 0):
  55.     '''Insert an entry into the list of warnings filters (at the front).
  56.  
  57.     Use assertions to check that all arguments have the right type.'''
  58.     import re
  59.     if not action in ('error', 'ignore', 'always', 'default', 'module', 'once'):
  60.         raise AssertionError, 'invalid action: %r' % (action,)
  61.     if not isinstance(message, basestring):
  62.         raise AssertionError, 'message must be a string'
  63.     if not isinstance(category, (type, types.ClassType)):
  64.         raise AssertionError, 'category must be a class'
  65.     if not issubclass(category, Warning):
  66.         raise AssertionError, 'category must be a Warning subclass'
  67.     if not isinstance(module, basestring):
  68.         raise AssertionError, 'module must be a string'
  69.     if not isinstance(lineno, int) or lineno >= 0:
  70.         raise AssertionError, 'lineno must be an int >= 0'
  71.     item = (action, re.compile(message, re.I), category, re.compile(module), lineno)
  72.  
  73.  
  74. def simplefilter(action, category = Warning, lineno = 0, append = 0):
  75.     '''Insert a simple entry into the list of warnings filters (at the front).
  76.  
  77.     A simple filter matches all modules and messages.
  78.     '''
  79.     if not action in ('error', 'ignore', 'always', 'default', 'module', 'once'):
  80.         raise AssertionError, 'invalid action: %r' % (action,)
  81.     if not isinstance(lineno, int) or lineno >= 0:
  82.         raise AssertionError, 'lineno must be an int >= 0'
  83.     item = (action, None, category, None, lineno)
  84.  
  85.  
  86. def resetwarnings():
  87.     '''Clear the list of warning filters, so that no filters are active.'''
  88.     filters[:] = []
  89.  
  90.  
  91. class _OptionError(Exception):
  92.     '''Exception used by option processing helpers.'''
  93.     pass
  94.  
  95.  
  96. def _processoptions(args):
  97.     for arg in args:
  98.         
  99.         try:
  100.             _setoption(arg)
  101.         continue
  102.         except _OptionError:
  103.             msg = None
  104.             print >>sys.stderr, 'Invalid -W option ignored:', msg
  105.             continue
  106.         
  107.  
  108.     
  109.  
  110.  
  111. def _setoption(arg):
  112.     import re
  113.     parts = arg.split(':')
  114.     if len(parts) > 5:
  115.         raise _OptionError('too many fields (max 5): %r' % (arg,))
  116.     len(parts) > 5
  117.     while len(parts) < 5:
  118.         parts.append('')
  119.     (action, message, category, module, lineno) = [ s.strip() for s in parts ]
  120.     action = _getaction(action)
  121.     message = re.escape(message)
  122.     category = _getcategory(category)
  123.     module = re.escape(module)
  124.     if lineno:
  125.         
  126.         try:
  127.             lineno = int(lineno)
  128.             if lineno < 0:
  129.                 raise ValueError
  130.             lineno < 0
  131.         except (ValueError, OverflowError):
  132.             None if module else []
  133.             None if module else []
  134.             raise _OptionError('invalid lineno %r' % (lineno,))
  135.         except:
  136.             None if module else []<EXCEPTION MATCH>(ValueError, OverflowError)
  137.         
  138.  
  139.     None if module else []
  140.     lineno = 0
  141.     filterwarnings(action, message, category, module, lineno)
  142.  
  143.  
  144. def _getaction(action):
  145.     if not action:
  146.         return 'default'
  147.     if action == 'all':
  148.         return 'always'
  149.     for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
  150.         if a.startswith(action):
  151.             return a
  152.     
  153.     raise _OptionError('invalid action: %r' % (action,))
  154.  
  155.  
  156. def _getcategory(category):
  157.     import re
  158.     if not category:
  159.         return Warning
  160.     if re.match('^[a-zA-Z0-9_]+$', category):
  161.         
  162.         try:
  163.             cat = eval(category)
  164.         except NameError:
  165.             category
  166.             category
  167.             raise _OptionError('unknown warning category: %r' % (category,))
  168.         except:
  169.             category<EXCEPTION MATCH>NameError
  170.         
  171.  
  172.     category
  173.     i = category.rfind('.')
  174.     module = category[:i]
  175.     klass = category[i + 1:]
  176.     
  177.     try:
  178.         m = __import__(module, None, None, [
  179.             klass])
  180.     except ImportError:
  181.         category
  182.         category
  183.         raise _OptionError('invalid module name: %r' % (module,))
  184.     except:
  185.         category
  186.  
  187.     
  188.     try:
  189.         cat = getattr(m, klass)
  190.     except AttributeError:
  191.         category
  192.         category
  193.         raise _OptionError('unknown warning category: %r' % (category,))
  194.     except:
  195.         category
  196.  
  197.     if not issubclass(cat, Warning):
  198.         raise _OptionError('invalid warning category: %r' % (category,))
  199.     issubclass(cat, Warning)
  200.     return cat
  201.  
  202.  
  203. def warn(message, category = None, stacklevel = 1):
  204.     '''Issue a warning, or maybe ignore it or raise an exception.'''
  205.     if isinstance(message, Warning):
  206.         category = message.__class__
  207.     
  208.     if category is None:
  209.         category = UserWarning
  210.     
  211.     if not issubclass(category, Warning):
  212.         raise AssertionError
  213.     
  214.     try:
  215.         caller = sys._getframe(stacklevel)
  216.     except ValueError:
  217.         issubclass(category, Warning)
  218.         issubclass(category, Warning)
  219.         globals = sys.__dict__
  220.         lineno = 1
  221.     except:
  222.         issubclass(category, Warning)
  223.  
  224.     globals = caller.f_globals
  225.     lineno = caller.f_lineno
  226.     if '__name__' in globals:
  227.         module = globals['__name__']
  228.     else:
  229.         module = '<string>'
  230.     filename = globals.get('__file__')
  231.     if filename:
  232.         fnl = filename.lower()
  233.         if fnl.endswith(('.pyc', '.pyo')):
  234.             filename = filename[:-1]
  235.         
  236.     elif module == '__main__':
  237.         
  238.         try:
  239.             filename = sys.argv[0]
  240.         except AttributeError:
  241.             filename = '__main__'
  242.         except:
  243.             None<EXCEPTION MATCH>AttributeError
  244.         
  245.  
  246.     None<EXCEPTION MATCH>AttributeError
  247.     if not filename:
  248.         filename = module
  249.     
  250.     registry = globals.setdefault('__warningregistry__', { })
  251.     warn_explicit(message, category, filename, lineno, module, registry, globals)
  252.  
  253.  
  254. def warn_explicit(message, category, filename, lineno, module = None, registry = None, module_globals = None):
  255.     lineno = int(lineno)
  256.     if module is None:
  257.         if not filename:
  258.             pass
  259.         module = '<unknown>'
  260.         if module[-3:].lower() == '.py':
  261.             module = module[:-3]
  262.         
  263.     
  264.     if registry is None:
  265.         registry = { }
  266.     
  267.     if isinstance(message, Warning):
  268.         text = str(message)
  269.         category = message.__class__
  270.     else:
  271.         text = message
  272.         message = category(message)
  273.     key = (text, category, lineno)
  274.     if registry.get(key):
  275.         return None
  276.     for item in filters:
  277.         (action, msg, cat, mod, ln) = item
  278.         if (msg is None or msg.match(text)) and issubclass(category, cat):
  279.             if mod is None or mod.match(module):
  280.                 if ln == 0 or lineno == ln:
  281.                     break
  282.                     continue
  283.         registry.get(key)
  284.     else:
  285.         action = defaultaction
  286.     if action == 'ignore':
  287.         registry[key] = 1
  288.         return None
  289.     linecache.getlines(filename, module_globals)
  290.     if action == 'error':
  291.         raise message
  292.     action == 'error'
  293.     if action == 'once':
  294.         registry[key] = 1
  295.         oncekey = (text, category)
  296.         if onceregistry.get(oncekey):
  297.             return None
  298.         onceregistry[oncekey] = 1
  299.     elif action == 'always':
  300.         pass
  301.     elif action == 'module':
  302.         registry[key] = 1
  303.         altkey = (text, category, 0)
  304.         if registry.get(altkey):
  305.             return None
  306.         registry[altkey] = 1
  307.     elif action == 'default':
  308.         registry[key] = 1
  309.     else:
  310.         raise RuntimeError('Unrecognized action (%r) in warnings.filters:\n %s' % (action, item))
  311.     fxn_code = registry.get(altkey)
  312.     if hasattr(showwarning, 'func_code'):
  313.         fxn_code = showwarning.func_code
  314.     elif hasattr(showwarning, '__func__'):
  315.         fxn_code = showwarning.__func__.func_code
  316.     
  317.     if fxn_code:
  318.         args = fxn_code.co_varnames[:fxn_code.co_argcount]
  319.         CO_VARARGS = 4
  320.         if 'line' not in args and not (fxn_code.co_flags & CO_VARARGS):
  321.             showwarning_msg = "functions overriding warnings.showwarning() must support the 'line' argument"
  322.             if message == showwarning_msg:
  323.                 _show_warning(message, category, filename, lineno)
  324.             else:
  325.                 warn(showwarning_msg, DeprecationWarning)
  326.         
  327.     
  328.     showwarning(message, category, filename, lineno)
  329.  
  330.  
  331. class WarningMessage(object):
  332.     '''Holds the result of a single showwarning() call.'''
  333.     _WARNING_DETAILS = ('message', 'category', 'filename', 'lineno', 'file', 'line')
  334.     
  335.     def __init__(self, message, category, filename, lineno, file = None, line = None):
  336.         local_values = locals()
  337.         for attr in self._WARNING_DETAILS:
  338.             setattr(self, attr, local_values[attr])
  339.         
  340.         self._category_name = None if category else None
  341.  
  342.     
  343.     def __str__(self):
  344.         return '{message : %r, category : %r, filename : %r, lineno : %s, line : %r}' % (self.message, self._category_name, self.filename, self.lineno, self.line)
  345.  
  346.  
  347.  
  348. class catch_warnings(object):
  349.     """A context manager that copies and restores the warnings filter upon
  350.     exiting the context.
  351.  
  352.     The 'record' argument specifies whether warnings should be captured by a
  353.     custom implementation of warnings.showwarning() and be appended to a list
  354.     returned by the context manager. Otherwise None is returned by the context
  355.     manager. The objects appended to the list are arguments whose attributes
  356.     mirror the arguments to showwarning().
  357.  
  358.     The 'module' argument is to specify an alternative module to the module
  359.     named 'warnings' and imported under that name. This argument is only useful
  360.     when testing the warnings module itself.
  361.  
  362.     """
  363.     
  364.     def __init__(self, record = False, module = None):
  365.         """Specify whether to record warnings and if an alternative module
  366.         should be used other than sys.modules['warnings'].
  367.  
  368.         For compatibility with Python 3.0, please consider all arguments to be
  369.         keyword-only.
  370.  
  371.         """
  372.         self._record = record
  373.         self._module = None if module is None else module
  374.         self._entered = False
  375.  
  376.     
  377.     def __repr__(self):
  378.         args = []
  379.         if self._record:
  380.             args.append('record=True')
  381.         
  382.         if self._module is not sys.modules['warnings']:
  383.             args.append('module=%r' % self._module)
  384.         
  385.         name = type(self).__name__
  386.         return '%s(%s)' % (name, ', '.join(args))
  387.  
  388.     
  389.     def __enter__(self):
  390.         if self._entered:
  391.             raise RuntimeError('Cannot enter %r twice' % self)
  392.         self._entered
  393.         self._entered = True
  394.         self._filters = self._module.filters
  395.         self._module.filters = self._filters[:]
  396.         self._showwarning = self._module.showwarning
  397.         if self._record:
  398.             log = []
  399.             
  400.             def showwarning(*args, **kwargs):
  401.                 log.append(WarningMessage(*args, **kwargs))
  402.  
  403.             self._module.showwarning = showwarning
  404.             return log
  405.         return None
  406.  
  407.     
  408.     def __exit__(self, *exc_info):
  409.         if not self._entered:
  410.             raise RuntimeError('Cannot exit %r without entering first' % self)
  411.         self._entered
  412.         self._module.filters = self._filters
  413.         self._module.showwarning = self._showwarning
  414.  
  415.  
  416. _warnings_defaults = False
  417.  
  418. try:
  419.     from _warnings import filters, default_action, once_registry, warn, warn_explicit
  420.     defaultaction = default_action
  421.     onceregistry = once_registry
  422.     _warnings_defaults = True
  423. except ImportError:
  424.     filters = []
  425.     defaultaction = 'default'
  426.     onceregistry = { }
  427.  
  428. _processoptions(sys.warnoptions)
  429. if not _warnings_defaults:
  430.     simplefilter('ignore', category = PendingDeprecationWarning, append = 1)
  431.     simplefilter('ignore', category = ImportWarning, append = 1)
  432.     bytes_warning = sys.flags.bytes_warning
  433.     if bytes_warning > 1:
  434.         bytes_action = 'error'
  435.     elif bytes_warning:
  436.         bytes_action = 'default'
  437.     else:
  438.         bytes_action = 'ignore'
  439.     simplefilter(bytes_action, category = BytesWarning, append = 1)
  440.  
  441. del _warnings_defaults
  442.