##// END OF EJS Templates
Reset the interactive namespace __warningregistry__ before executing code...
Reset the interactive namespace __warningregistry__ before executing code Fixes #6611. Idea: Right now, people often don't see important warnings when running code in IPython, because (to a first approximation) any given warning will only issue once per session. Blink and you'll miss it! This is a very common contributor to confused emails to numpy-discussion. E.g.: In [5]: 1 / my_array_with_random_contents /home/njs/.user-python2.7-64bit-3/bin/ipython:1: RuntimeWarning: divide by zero encountered in divide #!/home/njs/.user-python2.7-64bit-3/bin/python Out[5]: array([ 1.77073316, -2.29765021, -2.01800811, ..., 1.13871243, -1.08302964, -8.6185091 ]) Oo, right, guess I gotta be careful of those zeros -- thanks, numpy, for giving me that warning! A few days later: In [592]: 1 / some_other_array Out[592]: array([ 3.07735763, 0.50769289, 0.83984078, ..., -0.67563917, -0.85736257, -1.36511271]) Oops, it turns out that this array had a zero in it too, and that's going to bite me later. But no warning this time! The effect of this commit is to make it so that warnings triggered by the code in cell 5 do *not* suppress warnings triggered by the code in cell 592. Note that this only applies to warnings triggered *directly* by code entered interactively -- if somepkg.foo() calls anotherpkg.bad_func() which issues a warning, then this warning will still only be displayed once, even if multiple cells call somepkg.foo(). But if cell 5 and cell 592 both call anotherpkg.bad_func() directly, then both will get warnings. (Important exception: if foo() is defined *interactively*, and calls anotherpkg.bad_func(), then every cell that calls foo() will display the warning again. This is unavoidable without fixes to CPython upstream.) Explanation: Python's warning system has some weird quirks. By default, it tries to suppress duplicate warnings, where "duplicate" means the same warning message triggered twice by the same line of code. This requires determining which line of code is responsible for triggering a warning, and this is controlled by the stacklevel= argument to warnings.warn. Basically, though, the idea is that if foo() calls bar() which calls baz() which calls some_deprecated_api(), then baz() will get counted as being "responsible", and the warning system will make a note that the usage of some_deprecated_api() inside baz() has already been warned about and doesn't need to be warned about again. So far so good. To accomplish this, obviously, there has to be a record of somewhere which line this was. You might think that this would be done by recording the filename:linenumber pair in a dict inside the warnings module, or something like that. You would be wrong. What actually happens is that the warnings module will use stack introspection to reach into baz()'s execution environment, create a global (module-level) variable there named __warningregistry__, and then, inside this dictionary, record just the line number. Basically, it assumes that any given module contains only one line 1, only one line 2, etc., so storing the filename is irrelevant. Obviously for interactive code this is totally wrong -- all cells share the same execution environment and global namespace, and they all contain a new line 1. Currently the warnings module treats these as if they were all the same line. In fact they are not the same line; once we have executed a given chunk of code, we will never see those particular lines again. As soon as a given chunk of code finishes executing, its line number labels become meaningless, and the corresponding warning registry entries become meaningless as well. Therefore, with this patch we delete the __warningregistry__ each time we execute a new block of code.

File last commit:

r13592:21d42268
r18548:61431d7d
Show More
coloransi.py
187 lines | 6.8 KiB | text/x-python | PythonLexer
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 # -*- coding: utf-8 -*-
"""Tools for coloring text in ANSI terminals.
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 """
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
#*****************************************************************************
fperez
Small fix in ultraTB, and fix autocall....
r88 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 #
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
import os
Brian Granger
ipstruct.py => utils/ipstruct.py and imports updated.
r2030 from IPython.utils.ipstruct import Struct
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Thomas Kluyver
Refactor prompt handling into new prompt manager.
r5495 color_templates = (
Fernando Perez
Cleaner version of color table by P. Wang.
r1593 # Dark colors
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 ("Black" , "0;30"),
("Red" , "0;31"),
("Green" , "0;32"),
("Brown" , "0;33"),
("Blue" , "0;34"),
("Purple" , "0;35"),
("Cyan" , "0;36"),
("LightGray" , "0;37"),
Fernando Perez
Cleaner version of color table by P. Wang.
r1593 # Light colors
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 ("DarkGray" , "1;30"),
("LightRed" , "1;31"),
("LightGreen" , "1;32"),
("Yellow" , "1;33"),
("LightBlue" , "1;34"),
("LightPurple" , "1;35"),
("LightCyan" , "1;36"),
Bernardo B. Marques
remove all trailling spaces
r4872 ("White" , "1;37"),
Fernando Perez
Cleaner version of color table by P. Wang.
r1593 # Blinking colors. Probably should not be used in anything serious.
("BlinkBlack" , "5;30"),
("BlinkRed" , "5;31"),
("BlinkGreen" , "5;32"),
("BlinkYellow" , "5;33"),
("BlinkBlue" , "5;34"),
("BlinkPurple" , "5;35"),
("BlinkCyan" , "5;36"),
("BlinkLightGray", "5;37"),
)
Fernando Perez
Fix problem with windows installer script: html docs were not found.
r1589
Thomas Kluyver
Refactor prompt handling into new prompt manager.
r5495 def make_color_table(in_class):
"""Build a set of color attributes in a class.
Thomas Kluyver
Various minor docs fixes
r13592 Helper function for building the :class:`TermColors` and
:class`InputTermColors`.
"""
Fernando Perez
Add 2 lines accidentally removed in previous commit
r1594 for name,value in color_templates:
setattr(in_class,name,in_class._base % value)
Fernando Perez
Fix problem with windows installer script: html docs were not found.
r1589
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 class TermColors:
"""Color escape sequences.
Bernardo B. Marques
remove all trailling spaces
r4872 This class defines the escape sequences for all the standard (ANSI?)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 colors in terminals. Also defines a NoColor escape which is just the null
string, suitable for defining 'dummy' color schemes in terminals which get
confused by color escapes.
This class should be used as a mixin for building color schemes."""
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 NoColor = '' # for color schemes in color-less terminals.
Normal = '\033[0m' # Reset normal coloring
_base = '\033[%sm' # Template for all other colors
# Build the actual color table as a set of class attributes:
make_color_table(TermColors)
class InputTermColors:
"""Color escape sequences for input prompts.
This class is similar to TermColors, but the escapes are wrapped in \001
and \002 so that readline can properly know the length of each line and
can wrap lines accordingly. Use this class for any colored text which
needs to be used in input prompts, such as in calls to raw_input().
Bernardo B. Marques
remove all trailling spaces
r4872 This class defines the escape sequences for all the standard (ANSI?)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 colors in terminals. Also defines a NoColor escape which is just the null
string, suitable for defining 'dummy' color schemes in terminals which get
confused by color escapes.
This class should be used as a mixin for building color schemes."""
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 NoColor = '' # for color schemes in color-less terminals.
fperez
- applied Nicolas Pernetty's patch to improve support for (X)Emacs under Win32....
r550
fperez
Small fix with emacs term identification
r564 if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs':
fperez
- applied Nicolas Pernetty's patch to improve support for (X)Emacs under Win32....
r550 # (X)emacs on W32 gets confused with \001 and \002 so we remove them
Normal = '\033[0m' # Reset normal coloring
_base = '\033[%sm' # Template for all other colors
else:
Normal = '\001\033[0m\002' # Reset normal coloring
_base = '\001\033[%sm\002' # Template for all other colors
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
# Build the actual color table as a set of class attributes:
make_color_table(InputTermColors)
Thomas Kluyver
Refactor prompt handling into new prompt manager.
r5495 class NoColors:
"""This defines all the same names as the colour classes, but maps them to
empty strings, so it can easily be substituted to turn off colours."""
NoColor = ''
MinRK
add missing Normal on NoColors...
r7580 Normal = ''
Thomas Kluyver
Refactor prompt handling into new prompt manager.
r5495
for name, value in color_templates:
setattr(NoColors, name, '')
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 class ColorScheme:
"""Generic color scheme class. Just a name and a Struct."""
def __init__(self,__scheme_name_,colordict=None,**colormap):
self.name = __scheme_name_
if colordict is None:
self.colors = Struct(**colormap)
else:
self.colors = Struct(colordict)
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46
def copy(self,name=None):
"""Return a full copy of the object, optionally renaming it."""
if name is None:
name = self.name
Brian Granger
First draft of refactored ipstruct.py.
r2077 return ColorScheme(name, self.colors.dict())
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 class ColorSchemeTable(dict):
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 """General class to handle tables of color schemes.
It's basically a dict of color schemes with a couple of shorthand
attributes and some convenient methods.
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 active_scheme_name -> obvious
active_colors -> actual color table of the active scheme"""
def __init__(self,scheme_list=None,default_scheme=''):
"""Create a table of color schemes.
The table can be created empty and manually filled or it can be
created with a list of valid color schemes AND the specification for
the default active scheme.
"""
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 # create object attributes to be set later
self.active_scheme_name = ''
self.active_colors = None
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 if scheme_list:
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 if default_scheme == '':
Bradley M. Froehle
Apply most 2to3 raise fixes....
r7843 raise ValueError('you must specify the default color scheme')
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 for scheme in scheme_list:
self.add_scheme(scheme)
self.set_active_scheme(default_scheme)
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 def copy(self):
"""Return full copy of object"""
return ColorSchemeTable(self.values(),self.active_scheme_name)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 def add_scheme(self,new_scheme):
"""Add a new color scheme to the table."""
if not isinstance(new_scheme,ColorScheme):
Bradley M. Froehle
Apply most 2to3 raise fixes....
r7843 raise ValueError('ColorSchemeTable only accepts ColorScheme instances')
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self[new_scheme.name] = new_scheme
Bernardo B. Marques
remove all trailling spaces
r4872
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 def set_active_scheme(self,scheme,case_sensitive=0):
"""Set the currently active scheme.
Names are by default compared in a case-insensitive way, but this can
be changed by setting the parameter case_sensitive to true."""
Thomas Kluyver
Miscellaneous Py 3 fixes
r13358 scheme_names = list(self.keys())
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 if case_sensitive:
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 valid_schemes = scheme_names
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 scheme_test = scheme
else:
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 valid_schemes = [s.lower() for s in scheme_names]
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 scheme_test = scheme.lower()
try:
scheme_idx = valid_schemes.index(scheme_test)
except ValueError:
Bradley M. Froehle
Apply most 2to3 raise fixes....
r7843 raise ValueError('Unrecognized color scheme: ' + scheme + \
'\nValid schemes: '+str(scheme_names).replace("'', ",''))
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 else:
fperez
- Fairly significant changes to include Vivian's patches for improved pdb...
r46 active = scheme_names[scheme_idx]
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self.active_scheme_name = active
self.active_colors = self[active].colors
# Now allow using '' as an index for the current active scheme
self[''] = self[active]