##// END OF EJS Templates
Finishing work on configurables, plugins and extensions.
Brian Granger -
Show More
@@ -0,0 +1,51 b''
1 # encoding: utf-8
2 """IPython plugins.
3
4 Authors:
5
6 * Brian Granger
7 """
8
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010 The IPython Development Team
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
19
20 from IPython.config.configurable import Configurable
21 from IPython.utils.traitlets import Dict
22
23 #-----------------------------------------------------------------------------
24 # Main class
25 #-----------------------------------------------------------------------------
26
27 class PluginManager(Configurable):
28 """A manager for IPython plugins."""
29
30 plugins = Dict({})
31
32 def __init__(self, config=None):
33 super(PluginManager, self).__init__(config=config)
34
35 def register_plugin(self, name, plugin):
36 if not isinstance(plugin, Plugin):
37 raise TypeError('Expected Plugin, got: %r' % plugin)
38 if self.plugins.has_key(name):
39 raise KeyError('Plugin with name already exists: %r' % name)
40 self.plugins[name] = plugin
41
42 def unregister_plugin(self, name):
43 del self.plugins[name]
44
45 def get_plugin(self, name, default=None):
46 return self.plugins.get(name, default)
47
48
49 class Plugin(Configurable):
50 """Base class for IPython plugins."""
51 pass
@@ -0,0 +1,46 b''
1 """Tests for plugin.py"""
2
3 #-----------------------------------------------------------------------------
4 # Imports
5 #-----------------------------------------------------------------------------
6
7 from unittest import TestCase
8
9 from IPython.core.plugin import Plugin, PluginManager
10
11 #-----------------------------------------------------------------------------
12 # Tests
13 #-----------------------------------------------------------------------------
14
15 class FooPlugin(Plugin):
16 pass
17
18
19 class BarPlugin(Plugin):
20 pass
21
22
23 class BadPlugin(object):
24 pass
25
26
27 class PluginTest(TestCase):
28
29 def setUp(self):
30 self.manager = PluginManager()
31
32 def test_register_get(self):
33 self.assertEquals(None, self.manager.get_plugin('foo'))
34 foo = FooPlugin()
35 self.manager.register_plugin('foo', foo)
36 self.assertEquals(foo, self.manager.get_plugin('foo'))
37 bar = BarPlugin()
38 self.assertRaises(KeyError, self.manager.register_plugin, 'foo', bar)
39 bad = BadPlugin()
40 self.assertRaises(TypeError, self.manager.register_plugin, 'bad')
41
42 def test_unregister(self):
43 foo = FooPlugin()
44 self.manager.register_plugin('foo', foo)
45 self.manager.unregister_plugin('foo')
46 self.assertEquals(None, self.manager.get_plugin('foo'))
@@ -1,259 +1,259 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 System command aliases.
4 System command aliases.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import __builtin__
23 import __builtin__
24 import keyword
24 import keyword
25 import os
25 import os
26 import re
26 import re
27 import sys
27 import sys
28
28
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.core.splitinput import split_user_input
30 from IPython.core.splitinput import split_user_input
31
31
32 from IPython.utils.traitlets import List, Instance
32 from IPython.utils.traitlets import List, Instance
33 from IPython.utils.autoattr import auto_attr
33 from IPython.utils.autoattr import auto_attr
34 from IPython.utils.warn import warn, error
34 from IPython.utils.warn import warn, error
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 # This is used as the pattern for calls to split_user_input.
40 # This is used as the pattern for calls to split_user_input.
41 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
41 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
42
42
43 def default_aliases():
43 def default_aliases():
44 # Make some aliases automatically
44 # Make some aliases automatically
45 # Prepare list of shell aliases to auto-define
45 # Prepare list of shell aliases to auto-define
46 if os.name == 'posix':
46 if os.name == 'posix':
47 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
47 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
48 'mv mv -i','rm rm -i','cp cp -i',
48 'mv mv -i','rm rm -i','cp cp -i',
49 'cat cat','less less','clear clear',
49 'cat cat','less less','clear clear',
50 # a better ls
50 # a better ls
51 'ls ls -F',
51 'ls ls -F',
52 # long ls
52 # long ls
53 'll ls -lF')
53 'll ls -lF')
54 # Extra ls aliases with color, which need special treatment on BSD
54 # Extra ls aliases with color, which need special treatment on BSD
55 # variants
55 # variants
56 ls_extra = ( # color ls
56 ls_extra = ( # color ls
57 'lc ls -F -o --color',
57 'lc ls -F -o --color',
58 # ls normal files only
58 # ls normal files only
59 'lf ls -F -o --color %l | grep ^-',
59 'lf ls -F -o --color %l | grep ^-',
60 # ls symbolic links
60 # ls symbolic links
61 'lk ls -F -o --color %l | grep ^l',
61 'lk ls -F -o --color %l | grep ^l',
62 # directories or links to directories,
62 # directories or links to directories,
63 'ldir ls -F -o --color %l | grep /$',
63 'ldir ls -F -o --color %l | grep /$',
64 # things which are executable
64 # things which are executable
65 'lx ls -F -o --color %l | grep ^-..x',
65 'lx ls -F -o --color %l | grep ^-..x',
66 )
66 )
67 # The BSDs don't ship GNU ls, so they don't understand the
67 # The BSDs don't ship GNU ls, so they don't understand the
68 # --color switch out of the box
68 # --color switch out of the box
69 if 'bsd' in sys.platform:
69 if 'bsd' in sys.platform:
70 ls_extra = ( # ls normal files only
70 ls_extra = ( # ls normal files only
71 'lf ls -lF | grep ^-',
71 'lf ls -lF | grep ^-',
72 # ls symbolic links
72 # ls symbolic links
73 'lk ls -lF | grep ^l',
73 'lk ls -lF | grep ^l',
74 # directories or links to directories,
74 # directories or links to directories,
75 'ldir ls -lF | grep /$',
75 'ldir ls -lF | grep /$',
76 # things which are executable
76 # things which are executable
77 'lx ls -lF | grep ^-..x',
77 'lx ls -lF | grep ^-..x',
78 )
78 )
79 default_aliases = default_aliases + ls_extra
79 default_aliases = default_aliases + ls_extra
80 elif os.name in ['nt','dos']:
80 elif os.name in ['nt','dos']:
81 default_aliases = ('ls dir /on',
81 default_aliases = ('ls dir /on',
82 'ddir dir /ad /on', 'ldir dir /ad /on',
82 'ddir dir /ad /on', 'ldir dir /ad /on',
83 'mkdir mkdir','rmdir rmdir','echo echo',
83 'mkdir mkdir','rmdir rmdir','echo echo',
84 'ren ren','cls cls','copy copy')
84 'ren ren','cls cls','copy copy')
85 else:
85 else:
86 default_aliases = ()
86 default_aliases = ()
87 return [s.split(None,1) for s in default_aliases]
87 return [s.split(None,1) for s in default_aliases]
88
88
89
89
90 class AliasError(Exception):
90 class AliasError(Exception):
91 pass
91 pass
92
92
93
93
94 class InvalidAliasError(AliasError):
94 class InvalidAliasError(AliasError):
95 pass
95 pass
96
96
97
97
98 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
99 # Main AliasManager class
99 # Main AliasManager class
100 #-----------------------------------------------------------------------------
100 #-----------------------------------------------------------------------------
101
101
102
102
103 class AliasManager(Configurable):
103 class AliasManager(Configurable):
104
104
105 default_aliases = List(default_aliases(), config=True)
105 default_aliases = List(default_aliases(), config=True)
106 user_aliases = List(default_value=[], config=True)
106 user_aliases = List(default_value=[], config=True)
107 shell = Instance('IPython.core.iplib.InteractiveShell')
107 shell = Instance('IPython.core.iplib.InteractiveShellABC')
108
108
109 def __init__(self, shell, config=None):
109 def __init__(self, shell, config=None):
110 super(AliasManager, self).__init__(config=config)
110 super(AliasManager, self).__init__(config=config)
111 self.alias_table = {}
111 self.alias_table = {}
112 self.exclude_aliases()
112 self.exclude_aliases()
113 self.init_aliases()
113 self.init_aliases()
114 self.shell = shell
114 self.shell = shell
115
115
116 def __contains__(self, name):
116 def __contains__(self, name):
117 if name in self.alias_table:
117 if name in self.alias_table:
118 return True
118 return True
119 else:
119 else:
120 return False
120 return False
121
121
122 @property
122 @property
123 def aliases(self):
123 def aliases(self):
124 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
124 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
125
125
126 def exclude_aliases(self):
126 def exclude_aliases(self):
127 # set of things NOT to alias (keywords, builtins and some magics)
127 # set of things NOT to alias (keywords, builtins and some magics)
128 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
128 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
129 no_alias.update(set(keyword.kwlist))
129 no_alias.update(set(keyword.kwlist))
130 no_alias.update(set(__builtin__.__dict__.keys()))
130 no_alias.update(set(__builtin__.__dict__.keys()))
131 self.no_alias = no_alias
131 self.no_alias = no_alias
132
132
133 def init_aliases(self):
133 def init_aliases(self):
134 # Load default aliases
134 # Load default aliases
135 for name, cmd in self.default_aliases:
135 for name, cmd in self.default_aliases:
136 self.soft_define_alias(name, cmd)
136 self.soft_define_alias(name, cmd)
137
137
138 # Load user aliases
138 # Load user aliases
139 for name, cmd in self.user_aliases:
139 for name, cmd in self.user_aliases:
140 self.soft_define_alias(name, cmd)
140 self.soft_define_alias(name, cmd)
141
141
142 def clear_aliases(self):
142 def clear_aliases(self):
143 self.alias_table.clear()
143 self.alias_table.clear()
144
144
145 def soft_define_alias(self, name, cmd):
145 def soft_define_alias(self, name, cmd):
146 """Define an alias, but don't raise on an AliasError."""
146 """Define an alias, but don't raise on an AliasError."""
147 try:
147 try:
148 self.define_alias(name, cmd)
148 self.define_alias(name, cmd)
149 except AliasError, e:
149 except AliasError, e:
150 error("Invalid alias: %s" % e)
150 error("Invalid alias: %s" % e)
151
151
152 def define_alias(self, name, cmd):
152 def define_alias(self, name, cmd):
153 """Define a new alias after validating it.
153 """Define a new alias after validating it.
154
154
155 This will raise an :exc:`AliasError` if there are validation
155 This will raise an :exc:`AliasError` if there are validation
156 problems.
156 problems.
157 """
157 """
158 nargs = self.validate_alias(name, cmd)
158 nargs = self.validate_alias(name, cmd)
159 self.alias_table[name] = (nargs, cmd)
159 self.alias_table[name] = (nargs, cmd)
160
160
161 def undefine_alias(self, name):
161 def undefine_alias(self, name):
162 if self.alias_table.has_key(name):
162 if self.alias_table.has_key(name):
163 del self.alias_table[name]
163 del self.alias_table[name]
164
164
165 def validate_alias(self, name, cmd):
165 def validate_alias(self, name, cmd):
166 """Validate an alias and return the its number of arguments."""
166 """Validate an alias and return the its number of arguments."""
167 if name in self.no_alias:
167 if name in self.no_alias:
168 raise InvalidAliasError("The name %s can't be aliased "
168 raise InvalidAliasError("The name %s can't be aliased "
169 "because it is a keyword or builtin." % name)
169 "because it is a keyword or builtin." % name)
170 if not (isinstance(cmd, basestring)):
170 if not (isinstance(cmd, basestring)):
171 raise InvalidAliasError("An alias command must be a string, "
171 raise InvalidAliasError("An alias command must be a string, "
172 "got: %r" % name)
172 "got: %r" % name)
173 nargs = cmd.count('%s')
173 nargs = cmd.count('%s')
174 if nargs>0 and cmd.find('%l')>=0:
174 if nargs>0 and cmd.find('%l')>=0:
175 raise InvalidAliasError('The %s and %l specifiers are mutually '
175 raise InvalidAliasError('The %s and %l specifiers are mutually '
176 'exclusive in alias definitions.')
176 'exclusive in alias definitions.')
177 return nargs
177 return nargs
178
178
179 def call_alias(self, alias, rest=''):
179 def call_alias(self, alias, rest=''):
180 """Call an alias given its name and the rest of the line."""
180 """Call an alias given its name and the rest of the line."""
181 cmd = self.transform_alias(alias, rest)
181 cmd = self.transform_alias(alias, rest)
182 try:
182 try:
183 self.shell.system(cmd)
183 self.shell.system(cmd)
184 except:
184 except:
185 self.shell.showtraceback()
185 self.shell.showtraceback()
186
186
187 def transform_alias(self, alias,rest=''):
187 def transform_alias(self, alias,rest=''):
188 """Transform alias to system command string."""
188 """Transform alias to system command string."""
189 nargs, cmd = self.alias_table[alias]
189 nargs, cmd = self.alias_table[alias]
190
190
191 if ' ' in cmd and os.path.isfile(cmd):
191 if ' ' in cmd and os.path.isfile(cmd):
192 cmd = '"%s"' % cmd
192 cmd = '"%s"' % cmd
193
193
194 # Expand the %l special to be the user's input line
194 # Expand the %l special to be the user's input line
195 if cmd.find('%l') >= 0:
195 if cmd.find('%l') >= 0:
196 cmd = cmd.replace('%l', rest)
196 cmd = cmd.replace('%l', rest)
197 rest = ''
197 rest = ''
198 if nargs==0:
198 if nargs==0:
199 # Simple, argument-less aliases
199 # Simple, argument-less aliases
200 cmd = '%s %s' % (cmd, rest)
200 cmd = '%s %s' % (cmd, rest)
201 else:
201 else:
202 # Handle aliases with positional arguments
202 # Handle aliases with positional arguments
203 args = rest.split(None, nargs)
203 args = rest.split(None, nargs)
204 if len(args) < nargs:
204 if len(args) < nargs:
205 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
205 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
206 (alias, nargs, len(args)))
206 (alias, nargs, len(args)))
207 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
207 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
208 return cmd
208 return cmd
209
209
210 def expand_alias(self, line):
210 def expand_alias(self, line):
211 """ Expand an alias in the command line
211 """ Expand an alias in the command line
212
212
213 Returns the provided command line, possibly with the first word
213 Returns the provided command line, possibly with the first word
214 (command) translated according to alias expansion rules.
214 (command) translated according to alias expansion rules.
215
215
216 [ipython]|16> _ip.expand_aliases("np myfile.txt")
216 [ipython]|16> _ip.expand_aliases("np myfile.txt")
217 <16> 'q:/opt/np/notepad++.exe myfile.txt'
217 <16> 'q:/opt/np/notepad++.exe myfile.txt'
218 """
218 """
219
219
220 pre,fn,rest = split_user_input(line)
220 pre,fn,rest = split_user_input(line)
221 res = pre + self.expand_aliases(fn, rest)
221 res = pre + self.expand_aliases(fn, rest)
222 return res
222 return res
223
223
224 def expand_aliases(self, fn, rest):
224 def expand_aliases(self, fn, rest):
225 """Expand multiple levels of aliases:
225 """Expand multiple levels of aliases:
226
226
227 if:
227 if:
228
228
229 alias foo bar /tmp
229 alias foo bar /tmp
230 alias baz foo
230 alias baz foo
231
231
232 then:
232 then:
233
233
234 baz huhhahhei -> bar /tmp huhhahhei
234 baz huhhahhei -> bar /tmp huhhahhei
235
235
236 """
236 """
237 line = fn + " " + rest
237 line = fn + " " + rest
238
238
239 done = set()
239 done = set()
240 while 1:
240 while 1:
241 pre,fn,rest = split_user_input(line, shell_line_split)
241 pre,fn,rest = split_user_input(line, shell_line_split)
242 if fn in self.alias_table:
242 if fn in self.alias_table:
243 if fn in done:
243 if fn in done:
244 warn("Cyclic alias definition, repeated '%s'" % fn)
244 warn("Cyclic alias definition, repeated '%s'" % fn)
245 return ""
245 return ""
246 done.add(fn)
246 done.add(fn)
247
247
248 l2 = self.transform_alias(fn, rest)
248 l2 = self.transform_alias(fn, rest)
249 if l2 == line:
249 if l2 == line:
250 break
250 break
251 # ls -> ls -F should not recurse forever
251 # ls -> ls -F should not recurse forever
252 if l2.split(None,1)[0] == line.split(None,1)[0]:
252 if l2.split(None,1)[0] == line.split(None,1)[0]:
253 line = l2
253 line = l2
254 break
254 break
255 line=l2
255 line=l2
256 else:
256 else:
257 break
257 break
258
258
259 return line
259 return line
@@ -1,115 +1,115 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
4 A context manager for managing things injected into :mod:`__builtin__`.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23
23
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25 from IPython.core.quitter import Quitter
25 from IPython.core.quitter import Quitter
26
26
27 from IPython.utils.traitlets import Instance
27 from IPython.utils.traitlets import Instance
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class __BuiltinUndefined(object): pass
34 class __BuiltinUndefined(object): pass
35 BuiltinUndefined = __BuiltinUndefined()
35 BuiltinUndefined = __BuiltinUndefined()
36
36
37
37
38 class BuiltinTrap(Configurable):
38 class BuiltinTrap(Configurable):
39
39
40 shell = Instance('IPython.core.iplib.InteractiveShell')
40 shell = Instance('IPython.core.iplib.InteractiveShellABC')
41
41
42 def __init__(self, shell):
42 def __init__(self, shell):
43 super(BuiltinTrap, self).__init__(None)
43 super(BuiltinTrap, self).__init__(None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49
49
50 def __enter__(self):
50 def __enter__(self):
51 if self._nested_level == 0:
51 if self._nested_level == 0:
52 self.set()
52 self.set()
53 self._nested_level += 1
53 self._nested_level += 1
54 # I return self, so callers can use add_builtin in a with clause.
54 # I return self, so callers can use add_builtin in a with clause.
55 return self
55 return self
56
56
57 def __exit__(self, type, value, traceback):
57 def __exit__(self, type, value, traceback):
58 if self._nested_level == 1:
58 if self._nested_level == 1:
59 self.unset()
59 self.unset()
60 self._nested_level -= 1
60 self._nested_level -= 1
61 # Returning False will cause exceptions to propagate
61 # Returning False will cause exceptions to propagate
62 return False
62 return False
63
63
64 def add_builtin(self, key, value):
64 def add_builtin(self, key, value):
65 """Add a builtin and save the original."""
65 """Add a builtin and save the original."""
66 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
66 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
67 self._orig_builtins[key] = orig
67 self._orig_builtins[key] = orig
68 __builtin__.__dict__[key] = value
68 __builtin__.__dict__[key] = value
69
69
70 def remove_builtin(self, key):
70 def remove_builtin(self, key):
71 """Remove an added builtin and re-set the original."""
71 """Remove an added builtin and re-set the original."""
72 try:
72 try:
73 orig = self._orig_builtins.pop(key)
73 orig = self._orig_builtins.pop(key)
74 except KeyError:
74 except KeyError:
75 pass
75 pass
76 else:
76 else:
77 if orig is BuiltinUndefined:
77 if orig is BuiltinUndefined:
78 del __builtin__.__dict__[key]
78 del __builtin__.__dict__[key]
79 else:
79 else:
80 __builtin__.__dict__[key] = orig
80 __builtin__.__dict__[key] = orig
81
81
82 def set(self):
82 def set(self):
83 """Store ipython references in the __builtin__ namespace."""
83 """Store ipython references in the __builtin__ namespace."""
84 self.add_builtin('exit', Quitter(self.shell, 'exit'))
84 self.add_builtin('exit', Quitter(self.shell, 'exit'))
85 self.add_builtin('quit', Quitter(self.shell, 'quit'))
85 self.add_builtin('quit', Quitter(self.shell, 'quit'))
86 self.add_builtin('get_ipython', self.shell.get_ipython)
86 self.add_builtin('get_ipython', self.shell.get_ipython)
87
87
88 # Recursive reload function
88 # Recursive reload function
89 try:
89 try:
90 from IPython.lib import deepreload
90 from IPython.lib import deepreload
91 if self.shell.deep_reload:
91 if self.shell.deep_reload:
92 self.add_builtin('reload', deepreload.reload)
92 self.add_builtin('reload', deepreload.reload)
93 else:
93 else:
94 self.add_builtin('dreload', deepreload.reload)
94 self.add_builtin('dreload', deepreload.reload)
95 del deepreload
95 del deepreload
96 except ImportError:
96 except ImportError:
97 pass
97 pass
98
98
99 # Keep in the builtins a flag for when IPython is active. We set it
99 # Keep in the builtins a flag for when IPython is active. We set it
100 # with setdefault so that multiple nested IPythons don't clobber one
100 # with setdefault so that multiple nested IPythons don't clobber one
101 # another. Each will increase its value by one upon being activated,
101 # another. Each will increase its value by one upon being activated,
102 # which also gives us a way to determine the nesting level.
102 # which also gives us a way to determine the nesting level.
103 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
103 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
104
104
105 def unset(self):
105 def unset(self):
106 """Remove any builtins which might have been added by add_builtins, or
106 """Remove any builtins which might have been added by add_builtins, or
107 restore overwritten ones to their previous values."""
107 restore overwritten ones to their previous values."""
108 for key in self._orig_builtins.keys():
108 for key in self._orig_builtins.keys():
109 self.remove_builtin(key)
109 self.remove_builtin(key)
110 self._orig_builtins.clear()
110 self._orig_builtins.clear()
111 self._builtins_added = False
111 self._builtins_added = False
112 try:
112 try:
113 del __builtin__.__dict__['__IPYTHON__active']
113 del __builtin__.__dict__['__IPYTHON__active']
114 except KeyError:
114 except KeyError:
115 pass
115 pass
@@ -1,124 +1,126 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """A class for managing IPython extensions.
2 """A class for managing IPython extensions.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010 The IPython Development Team
10 # Copyright (C) 2010 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import os
20 import os
21 import sys
21 import sys
22
22
23 from IPython.config.configurable import Configurable
23 from IPython.config.configurable import Configurable
24 from IPython.utils.traitlets import Instance
24 from IPython.utils.traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Main class
27 # Main class
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class ExtensionManager(Configurable):
30 class ExtensionManager(Configurable):
31 """A class to manage IPython extensions.
31
32
32 shell = Instance('IPython.core.iplib.InteractiveShell')
33 An IPython extension is an importable Python module that has
34 a function with the signature::
35
36 def load_ipython_extension(ipython):
37 # Do things with ipython
38
39 This function is called after your extension is imported and the
40 currently active :class:`InteractiveShell` instance is passed as
41 the only argument. You can do anything you want with IPython at
42 that point, including defining new magic and aliases, adding new
43 components, etc.
44
45 The :func:`load_ipython_extension` will be called again is you
46 load or reload the extension again. It is up to the extension
47 author to add code to manage that.
48
49 You can put your extension modules anywhere you want, as long as
50 they can be imported by Python's standard import mechanism. However,
51 to make it easy to write extensions, you can also put your extensions
52 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
53 is added to ``sys.path`` automatically.
54 """
55
56 shell = Instance('IPython.core.iplib.InteractiveShellABC')
33
57
34 def __init__(self, shell, config=None):
58 def __init__(self, shell, config=None):
35 super(ExtensionManager, self).__init__(config=config)
59 super(ExtensionManager, self).__init__(config=config)
36 self.shell = shell
60 self.shell = shell
37 self.shell.on_trait_change(
61 self.shell.on_trait_change(
38 self._on_ipython_dir_changed, 'ipython_dir'
62 self._on_ipython_dir_changed, 'ipython_dir'
39 )
63 )
40
64
41 def __del__(self):
65 def __del__(self):
42 self.shell.on_trait_change(
66 self.shell.on_trait_change(
43 self._on_ipython_dir_changed, 'ipython_dir', remove=True
67 self._on_ipython_dir_changed, 'ipython_dir', remove=True
44 )
68 )
45
69
46 @property
70 @property
47 def ipython_extension_dir(self):
71 def ipython_extension_dir(self):
48 return os.path.join(self.shell.ipython_dir, u'extensions')
72 return os.path.join(self.shell.ipython_dir, u'extensions')
49
73
50 def _on_ipython_dir_changed(self):
74 def _on_ipython_dir_changed(self):
51 if not os.path.isdir(self.ipython_extension_dir):
75 if not os.path.isdir(self.ipython_extension_dir):
52 os.makedirs(self.ipython_extension_dir, mode = 0777)
76 os.makedirs(self.ipython_extension_dir, mode = 0777)
53
77
54 def load_extension(self, module_str):
78 def load_extension(self, module_str):
55 """Load an IPython extension by its module name.
79 """Load an IPython extension by its module name.
56
80
57 An IPython extension is an importable Python module that has
58 a function with the signature::
59
60 def load_ipython_extension(ipython):
61 # Do things with ipython
62
63 This function is called after your extension is imported and the
64 currently active :class:`InteractiveShell` instance is passed as
65 the only argument. You can do anything you want with IPython at
66 that point, including defining new magic and aliases, adding new
67 components, etc.
68
69 The :func:`load_ipython_extension` will be called again is you
70 load or reload the extension again. It is up to the extension
71 author to add code to manage that.
72
73 You can put your extension modules anywhere you want, as long as
74 they can be imported by Python's standard import mechanism. However,
75 to make it easy to write extensions, you can also put your extensions
76 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
77 is added to ``sys.path`` automatically.
78
79 If :func:`load_ipython_extension` returns anything, this function
81 If :func:`load_ipython_extension` returns anything, this function
80 will return that object.
82 will return that object.
81 """
83 """
82 from IPython.utils.syspathcontext import prepended_to_syspath
84 from IPython.utils.syspathcontext import prepended_to_syspath
83
85
84 if module_str not in sys.modules:
86 if module_str not in sys.modules:
85 with prepended_to_syspath(self.ipython_extension_dir):
87 with prepended_to_syspath(self.ipython_extension_dir):
86 __import__(module_str)
88 __import__(module_str)
87 mod = sys.modules[module_str]
89 mod = sys.modules[module_str]
88 return self._call_load_ipython_extension(mod)
90 return self._call_load_ipython_extension(mod)
89
91
90 def unload_extension(self, module_str):
92 def unload_extension(self, module_str):
91 """Unload an IPython extension by its module name.
93 """Unload an IPython extension by its module name.
92
94
93 This function looks up the extension's name in ``sys.modules`` and
95 This function looks up the extension's name in ``sys.modules`` and
94 simply calls ``mod.unload_ipython_extension(self)``.
96 simply calls ``mod.unload_ipython_extension(self)``.
95 """
97 """
96 if module_str in sys.modules:
98 if module_str in sys.modules:
97 mod = sys.modules[module_str]
99 mod = sys.modules[module_str]
98 self._call_unload_ipython_extension(mod)
100 self._call_unload_ipython_extension(mod)
99
101
100 def reload_extension(self, module_str):
102 def reload_extension(self, module_str):
101 """Reload an IPython extension by calling reload.
103 """Reload an IPython extension by calling reload.
102
104
103 If the module has not been loaded before,
105 If the module has not been loaded before,
104 :meth:`InteractiveShell.load_extension` is called. Otherwise
106 :meth:`InteractiveShell.load_extension` is called. Otherwise
105 :func:`reload` is called and then the :func:`load_ipython_extension`
107 :func:`reload` is called and then the :func:`load_ipython_extension`
106 function of the module, if it exists is called.
108 function of the module, if it exists is called.
107 """
109 """
108 from IPython.utils.syspathcontext import prepended_to_syspath
110 from IPython.utils.syspathcontext import prepended_to_syspath
109
111
110 with prepended_to_syspath(self.ipython_extension_dir):
112 with prepended_to_syspath(self.ipython_extension_dir):
111 if module_str in sys.modules:
113 if module_str in sys.modules:
112 mod = sys.modules[module_str]
114 mod = sys.modules[module_str]
113 reload(mod)
115 reload(mod)
114 self._call_load_ipython_extension(mod)
116 self._call_load_ipython_extension(mod)
115 else:
117 else:
116 self.load_extension(module_str)
118 self.load_extension(module_str)
117
119
118 def _call_load_ipython_extension(self, mod):
120 def _call_load_ipython_extension(self, mod):
119 if hasattr(mod, 'load_ipython_extension'):
121 if hasattr(mod, 'load_ipython_extension'):
120 return mod.load_ipython_extension(self.shell)
122 return mod.load_ipython_extension(self.shell)
121
123
122 def _call_unload_ipython_extension(self, mod):
124 def _call_unload_ipython_extension(self, mod):
123 if hasattr(mod, 'unload_ipython_extension'):
125 if hasattr(mod, 'unload_ipython_extension'):
124 return mod.unload_ipython_extension(self.shell) No newline at end of file
126 return mod.unload_ipython_extension(self.shell)
@@ -1,2511 +1,2523 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import bdb
22 import bdb
22 import codeop
23 import codeop
23 import exceptions
24 import exceptions
24 import new
25 import new
25 import os
26 import os
26 import re
27 import re
27 import string
28 import string
28 import sys
29 import sys
29 import tempfile
30 import tempfile
30 from contextlib import nested
31 from contextlib import nested
31
32
32 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
33 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
34 from IPython.core import prefilter
35 from IPython.core import prefilter
35 from IPython.core import shadowns
36 from IPython.core import shadowns
36 from IPython.core import ultratb
37 from IPython.core import ultratb
37 from IPython.core.alias import AliasManager
38 from IPython.core.alias import AliasManager
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.config.configurable import Configurable
40 from IPython.config.configurable import Configurable
40 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.error import TryNext, UsageError
42 from IPython.core.error import TryNext, UsageError
42 from IPython.core.extensions import ExtensionManager
43 from IPython.core.extensions import ExtensionManager
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
45 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.plugin import PluginManager
46 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.prompts import CachedOutput
49 from IPython.core.prompts import CachedOutput
48 from IPython.core.usage import interactive_usage, default_banner
50 from IPython.core.usage import interactive_usage, default_banner
49 import IPython.core.hooks
51 import IPython.core.hooks
50 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
51 from IPython.lib.inputhook import enable_gui
53 from IPython.lib.inputhook import enable_gui
52 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.pylabtools import pylab_activate
55 from IPython.lib.pylabtools import pylab_activate
54 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
55 from IPython.utils import pickleshare
57 from IPython.utils import pickleshare
56 from IPython.utils.doctestreload import doctest_reload
58 from IPython.utils.doctestreload import doctest_reload
57 from IPython.utils.ipstruct import Struct
59 from IPython.utils.ipstruct import Struct
58 from IPython.utils.io import Term, ask_yes_no
60 from IPython.utils.io import Term, ask_yes_no
59 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
60 from IPython.utils.process import (
62 from IPython.utils.process import (
61 abbrev_cwd,
63 abbrev_cwd,
62 getoutput,
64 getoutput,
63 getoutputerror
65 getoutputerror
64 )
66 )
65 # import IPython.utils.rlineimpl as readline
67 # import IPython.utils.rlineimpl as readline
66 from IPython.utils.strdispatch import StrDispatch
68 from IPython.utils.strdispatch import StrDispatch
67 from IPython.utils.syspathcontext import prepended_to_syspath
69 from IPython.utils.syspathcontext import prepended_to_syspath
68 from IPython.utils.terminal import toggle_set_term_title, set_term_title
70 from IPython.utils.terminal import toggle_set_term_title, set_term_title
69 from IPython.utils.warn import warn, error, fatal
71 from IPython.utils.warn import warn, error, fatal
70 from IPython.utils.traitlets import (
72 from IPython.utils.traitlets import (
71 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
73 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
72 )
74 )
73
75
74 # from IPython.utils import growl
76 # from IPython.utils import growl
75 # growl.start("IPython")
77 # growl.start("IPython")
76
78
77 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
78 # Globals
80 # Globals
79 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
80
82
81 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
85 raw_input_original = raw_input
84
86
85 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
89
88 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
89 # Utilities
91 # Utilities
90 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
91
93
92 ini_spaces_re = re.compile(r'^(\s+)')
94 ini_spaces_re = re.compile(r'^(\s+)')
93
95
94
96
95 def num_ini_spaces(strng):
97 def num_ini_spaces(strng):
96 """Return the number of initial spaces in a string"""
98 """Return the number of initial spaces in a string"""
97
99
98 ini_spaces = ini_spaces_re.match(strng)
100 ini_spaces = ini_spaces_re.match(strng)
99 if ini_spaces:
101 if ini_spaces:
100 return ini_spaces.end()
102 return ini_spaces.end()
101 else:
103 else:
102 return 0
104 return 0
103
105
104
106
105 def softspace(file, newvalue):
107 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
108 """Copied from code.py, to remove the dependency"""
107
109
108 oldvalue = 0
110 oldvalue = 0
109 try:
111 try:
110 oldvalue = file.softspace
112 oldvalue = file.softspace
111 except AttributeError:
113 except AttributeError:
112 pass
114 pass
113 try:
115 try:
114 file.softspace = newvalue
116 file.softspace = newvalue
115 except (AttributeError, TypeError):
117 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
118 # "attribute-less object" or "read-only attributes"
117 pass
119 pass
118 return oldvalue
120 return oldvalue
119
121
120
122
121 def no_op(*a, **kw): pass
123 def no_op(*a, **kw): pass
122
124
123 class SpaceInInput(exceptions.Exception): pass
125 class SpaceInInput(exceptions.Exception): pass
124
126
125 class Bunch: pass
127 class Bunch: pass
126
128
127 class InputList(list):
129 class InputList(list):
128 """Class to store user input.
130 """Class to store user input.
129
131
130 It's basically a list, but slices return a string instead of a list, thus
132 It's basically a list, but slices return a string instead of a list, thus
131 allowing things like (assuming 'In' is an instance):
133 allowing things like (assuming 'In' is an instance):
132
134
133 exec In[4:7]
135 exec In[4:7]
134
136
135 or
137 or
136
138
137 exec In[5:9] + In[14] + In[21:25]"""
139 exec In[5:9] + In[14] + In[21:25]"""
138
140
139 def __getslice__(self,i,j):
141 def __getslice__(self,i,j):
140 return ''.join(list.__getslice__(self,i,j))
142 return ''.join(list.__getslice__(self,i,j))
141
143
142
144
143 class SyntaxTB(ultratb.ListTB):
145 class SyntaxTB(ultratb.ListTB):
144 """Extension which holds some state: the last exception value"""
146 """Extension which holds some state: the last exception value"""
145
147
146 def __init__(self,color_scheme = 'NoColor'):
148 def __init__(self,color_scheme = 'NoColor'):
147 ultratb.ListTB.__init__(self,color_scheme)
149 ultratb.ListTB.__init__(self,color_scheme)
148 self.last_syntax_error = None
150 self.last_syntax_error = None
149
151
150 def __call__(self, etype, value, elist):
152 def __call__(self, etype, value, elist):
151 self.last_syntax_error = value
153 self.last_syntax_error = value
152 ultratb.ListTB.__call__(self,etype,value,elist)
154 ultratb.ListTB.__call__(self,etype,value,elist)
153
155
154 def clear_err_state(self):
156 def clear_err_state(self):
155 """Return the current error state and clear it"""
157 """Return the current error state and clear it"""
156 e = self.last_syntax_error
158 e = self.last_syntax_error
157 self.last_syntax_error = None
159 self.last_syntax_error = None
158 return e
160 return e
159
161
160
162
161 def get_default_editor():
163 def get_default_editor():
162 try:
164 try:
163 ed = os.environ['EDITOR']
165 ed = os.environ['EDITOR']
164 except KeyError:
166 except KeyError:
165 if os.name == 'posix':
167 if os.name == 'posix':
166 ed = 'vi' # the only one guaranteed to be there!
168 ed = 'vi' # the only one guaranteed to be there!
167 else:
169 else:
168 ed = 'notepad' # same in Windows!
170 ed = 'notepad' # same in Windows!
169 return ed
171 return ed
170
172
171
173
172 def get_default_colors():
174 def get_default_colors():
173 if sys.platform=='darwin':
175 if sys.platform=='darwin':
174 return "LightBG"
176 return "LightBG"
175 elif os.name=='nt':
177 elif os.name=='nt':
176 return 'Linux'
178 return 'Linux'
177 else:
179 else:
178 return 'Linux'
180 return 'Linux'
179
181
180
182
181 class SeparateStr(Str):
183 class SeparateStr(Str):
182 """A Str subclass to validate separate_in, separate_out, etc.
184 """A Str subclass to validate separate_in, separate_out, etc.
183
185
184 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
186 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
185 """
187 """
186
188
187 def validate(self, obj, value):
189 def validate(self, obj, value):
188 if value == '0': value = ''
190 if value == '0': value = ''
189 value = value.replace('\\n','\n')
191 value = value.replace('\\n','\n')
190 return super(SeparateStr, self).validate(obj, value)
192 return super(SeparateStr, self).validate(obj, value)
191
193
192
194
193 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
194 # Main IPython class
196 # Main IPython class
195 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
196
198
197
199
198 class InteractiveShell(Configurable, Magic):
200 class InteractiveShell(Configurable, Magic):
199 """An enhanced, interactive shell for Python."""
201 """An enhanced, interactive shell for Python."""
200
202
201 autocall = Enum((0,1,2), default_value=1, config=True)
203 autocall = Enum((0,1,2), default_value=1, config=True)
202 autoedit_syntax = CBool(False, config=True)
204 autoedit_syntax = CBool(False, config=True)
203 autoindent = CBool(True, config=True)
205 autoindent = CBool(True, config=True)
204 automagic = CBool(True, config=True)
206 automagic = CBool(True, config=True)
205 banner = Str('')
207 banner = Str('')
206 banner1 = Str(default_banner, config=True)
208 banner1 = Str(default_banner, config=True)
207 banner2 = Str('', config=True)
209 banner2 = Str('', config=True)
208 cache_size = Int(1000, config=True)
210 cache_size = Int(1000, config=True)
209 color_info = CBool(True, config=True)
211 color_info = CBool(True, config=True)
210 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
212 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
211 default_value=get_default_colors(), config=True)
213 default_value=get_default_colors(), config=True)
212 confirm_exit = CBool(True, config=True)
214 confirm_exit = CBool(True, config=True)
213 debug = CBool(False, config=True)
215 debug = CBool(False, config=True)
214 deep_reload = CBool(False, config=True)
216 deep_reload = CBool(False, config=True)
215 # This display_banner only controls whether or not self.show_banner()
217 # This display_banner only controls whether or not self.show_banner()
216 # is called when mainloop/interact are called. The default is False
218 # is called when mainloop/interact are called. The default is False
217 # because for the terminal based application, the banner behavior
219 # because for the terminal based application, the banner behavior
218 # is controlled by Global.display_banner, which IPythonApp looks at
220 # is controlled by Global.display_banner, which IPythonApp looks at
219 # to determine if *it* should call show_banner() by hand or not.
221 # to determine if *it* should call show_banner() by hand or not.
220 display_banner = CBool(False) # This isn't configurable!
222 display_banner = CBool(False) # This isn't configurable!
221 embedded = CBool(False)
223 embedded = CBool(False)
222 embedded_active = CBool(False)
224 embedded_active = CBool(False)
223 editor = Str(get_default_editor(), config=True)
225 editor = Str(get_default_editor(), config=True)
224 filename = Str("<ipython console>")
226 filename = Str("<ipython console>")
225 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
227 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
226 logstart = CBool(False, config=True)
228 logstart = CBool(False, config=True)
227 logfile = Str('', config=True)
229 logfile = Str('', config=True)
228 logappend = Str('', config=True)
230 logappend = Str('', config=True)
229 object_info_string_level = Enum((0,1,2), default_value=0,
231 object_info_string_level = Enum((0,1,2), default_value=0,
230 config=True)
232 config=True)
231 pager = Str('less', config=True)
233 pager = Str('less', config=True)
232 pdb = CBool(False, config=True)
234 pdb = CBool(False, config=True)
233 pprint = CBool(True, config=True)
235 pprint = CBool(True, config=True)
234 profile = Str('', config=True)
236 profile = Str('', config=True)
235 prompt_in1 = Str('In [\\#]: ', config=True)
237 prompt_in1 = Str('In [\\#]: ', config=True)
236 prompt_in2 = Str(' .\\D.: ', config=True)
238 prompt_in2 = Str(' .\\D.: ', config=True)
237 prompt_out = Str('Out[\\#]: ', config=True)
239 prompt_out = Str('Out[\\#]: ', config=True)
238 prompts_pad_left = CBool(True, config=True)
240 prompts_pad_left = CBool(True, config=True)
239 quiet = CBool(False, config=True)
241 quiet = CBool(False, config=True)
240
242
241 readline_use = CBool(True, config=True)
243 readline_use = CBool(True, config=True)
242 readline_merge_completions = CBool(True, config=True)
244 readline_merge_completions = CBool(True, config=True)
243 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
245 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
244 readline_remove_delims = Str('-/~', config=True)
246 readline_remove_delims = Str('-/~', config=True)
245 readline_parse_and_bind = List([
247 readline_parse_and_bind = List([
246 'tab: complete',
248 'tab: complete',
247 '"\C-l": clear-screen',
249 '"\C-l": clear-screen',
248 'set show-all-if-ambiguous on',
250 'set show-all-if-ambiguous on',
249 '"\C-o": tab-insert',
251 '"\C-o": tab-insert',
250 '"\M-i": " "',
252 '"\M-i": " "',
251 '"\M-o": "\d\d\d\d"',
253 '"\M-o": "\d\d\d\d"',
252 '"\M-I": "\d\d\d\d"',
254 '"\M-I": "\d\d\d\d"',
253 '"\C-r": reverse-search-history',
255 '"\C-r": reverse-search-history',
254 '"\C-s": forward-search-history',
256 '"\C-s": forward-search-history',
255 '"\C-p": history-search-backward',
257 '"\C-p": history-search-backward',
256 '"\C-n": history-search-forward',
258 '"\C-n": history-search-forward',
257 '"\e[A": history-search-backward',
259 '"\e[A": history-search-backward',
258 '"\e[B": history-search-forward',
260 '"\e[B": history-search-forward',
259 '"\C-k": kill-line',
261 '"\C-k": kill-line',
260 '"\C-u": unix-line-discard',
262 '"\C-u": unix-line-discard',
261 ], allow_none=False, config=True)
263 ], allow_none=False, config=True)
262
264
263 screen_length = Int(0, config=True)
265 screen_length = Int(0, config=True)
264
266
265 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
267 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
266 separate_in = SeparateStr('\n', config=True)
268 separate_in = SeparateStr('\n', config=True)
267 separate_out = SeparateStr('', config=True)
269 separate_out = SeparateStr('', config=True)
268 separate_out2 = SeparateStr('', config=True)
270 separate_out2 = SeparateStr('', config=True)
269
271
270 system_header = Str('IPython system call: ', config=True)
272 system_header = Str('IPython system call: ', config=True)
271 system_verbose = CBool(False, config=True)
273 system_verbose = CBool(False, config=True)
272 term_title = CBool(False, config=True)
274 term_title = CBool(False, config=True)
273 wildcards_case_sensitive = CBool(True, config=True)
275 wildcards_case_sensitive = CBool(True, config=True)
274 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
276 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
275 default_value='Context', config=True)
277 default_value='Context', config=True)
276
278
277 autoexec = List(allow_none=False)
279 autoexec = List(allow_none=False)
278
280
279 # class attribute to indicate whether the class supports threads or not.
281 # class attribute to indicate whether the class supports threads or not.
280 # Subclasses with thread support should override this as needed.
282 # Subclasses with thread support should override this as needed.
281 isthreaded = False
283 isthreaded = False
282
284
283 # Subcomponents of InteractiveShell
285 # Subcomponents of InteractiveShell
284 alias_manager = Instance('IPython.core.alias.AliasManager')
286 alias_manager = Instance('IPython.core.alias.AliasManager')
285 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
287 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
286 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
288 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
287 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
289 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
288 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
290 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
291 plugin_manager = Instance('IPython.core.plugin.PluginManager')
289
292
290 def __init__(self, config=None, ipython_dir=None, usage=None,
293 def __init__(self, config=None, ipython_dir=None, usage=None,
291 user_ns=None, user_global_ns=None,
294 user_ns=None, user_global_ns=None,
292 banner1=None, banner2=None, display_banner=None,
295 banner1=None, banner2=None, display_banner=None,
293 custom_exceptions=((),None)):
296 custom_exceptions=((),None)):
294
297
295 # This is where traits with a config_key argument are updated
298 # This is where traits with a config_key argument are updated
296 # from the values on config.
299 # from the values on config.
297 super(InteractiveShell, self).__init__(config=config)
300 super(InteractiveShell, self).__init__(config=config)
298
301
299 # These are relatively independent and stateless
302 # These are relatively independent and stateless
300 self.init_ipython_dir(ipython_dir)
303 self.init_ipython_dir(ipython_dir)
301 self.init_instance_attrs()
304 self.init_instance_attrs()
302 self.init_term_title()
305 self.init_term_title()
303 self.init_usage(usage)
306 self.init_usage(usage)
304 self.init_banner(banner1, banner2, display_banner)
307 self.init_banner(banner1, banner2, display_banner)
305
308
306 # Create namespaces (user_ns, user_global_ns, etc.)
309 # Create namespaces (user_ns, user_global_ns, etc.)
307 self.init_create_namespaces(user_ns, user_global_ns)
310 self.init_create_namespaces(user_ns, user_global_ns)
308 # This has to be done after init_create_namespaces because it uses
311 # This has to be done after init_create_namespaces because it uses
309 # something in self.user_ns, but before init_sys_modules, which
312 # something in self.user_ns, but before init_sys_modules, which
310 # is the first thing to modify sys.
313 # is the first thing to modify sys.
311 self.save_sys_module_state()
314 self.save_sys_module_state()
312 self.init_sys_modules()
315 self.init_sys_modules()
313
316
314 self.init_history()
317 self.init_history()
315 self.init_encoding()
318 self.init_encoding()
316 self.init_prefilter()
319 self.init_prefilter()
317
320
318 Magic.__init__(self, self)
321 Magic.__init__(self, self)
319
322
320 self.init_syntax_highlighting()
323 self.init_syntax_highlighting()
321 self.init_hooks()
324 self.init_hooks()
322 self.init_pushd_popd_magic()
325 self.init_pushd_popd_magic()
323 self.init_traceback_handlers(custom_exceptions)
326 self.init_traceback_handlers(custom_exceptions)
324 self.init_user_ns()
327 self.init_user_ns()
325 self.init_logger()
328 self.init_logger()
326 self.init_alias()
329 self.init_alias()
327 self.init_builtins()
330 self.init_builtins()
328
331
329 # pre_config_initialization
332 # pre_config_initialization
330 self.init_shadow_hist()
333 self.init_shadow_hist()
331
334
332 # The next section should contain averything that was in ipmaker.
335 # The next section should contain averything that was in ipmaker.
333 self.init_logstart()
336 self.init_logstart()
334
337
335 # The following was in post_config_initialization
338 # The following was in post_config_initialization
336 self.init_inspector()
339 self.init_inspector()
337 self.init_readline()
340 self.init_readline()
338 self.init_prompts()
341 self.init_prompts()
339 self.init_displayhook()
342 self.init_displayhook()
340 self.init_reload_doctest()
343 self.init_reload_doctest()
341 self.init_magics()
344 self.init_magics()
342 self.init_pdb()
345 self.init_pdb()
343 self.init_extension_manager()
346 self.init_extension_manager()
347 self.init_plugin_manager()
344 self.hooks.late_startup_hook()
348 self.hooks.late_startup_hook()
345
349
346 @classmethod
350 @classmethod
347 def instance(cls, *args, **kwargs):
351 def instance(cls, *args, **kwargs):
348 """Returns a global InteractiveShell instance."""
352 """Returns a global InteractiveShell instance."""
349 if not hasattr(cls, "_instance"):
353 if not hasattr(cls, "_instance"):
350 cls._instance = cls(*args, **kwargs)
354 cls._instance = cls(*args, **kwargs)
351 return cls._instance
355 return cls._instance
352
356
353 @classmethod
357 @classmethod
354 def initialized(cls):
358 def initialized(cls):
355 return hasattr(cls, "_instance")
359 return hasattr(cls, "_instance")
356
360
357 def get_ipython(self):
361 def get_ipython(self):
358 """Return the currently running IPython instance."""
362 """Return the currently running IPython instance."""
359 return self
363 return self
360
364
361 #-------------------------------------------------------------------------
365 #-------------------------------------------------------------------------
362 # Trait changed handlers
366 # Trait changed handlers
363 #-------------------------------------------------------------------------
367 #-------------------------------------------------------------------------
364
368
365 def _banner1_changed(self):
369 def _banner1_changed(self):
366 self.compute_banner()
370 self.compute_banner()
367
371
368 def _banner2_changed(self):
372 def _banner2_changed(self):
369 self.compute_banner()
373 self.compute_banner()
370
374
371 def _ipython_dir_changed(self, name, new):
375 def _ipython_dir_changed(self, name, new):
372 if not os.path.isdir(new):
376 if not os.path.isdir(new):
373 os.makedirs(new, mode = 0777)
377 os.makedirs(new, mode = 0777)
374
378
375 @property
379 @property
376 def usable_screen_length(self):
380 def usable_screen_length(self):
377 if self.screen_length == 0:
381 if self.screen_length == 0:
378 return 0
382 return 0
379 else:
383 else:
380 num_lines_bot = self.separate_in.count('\n')+1
384 num_lines_bot = self.separate_in.count('\n')+1
381 return self.screen_length - num_lines_bot
385 return self.screen_length - num_lines_bot
382
386
383 def _term_title_changed(self, name, new_value):
387 def _term_title_changed(self, name, new_value):
384 self.init_term_title()
388 self.init_term_title()
385
389
386 def set_autoindent(self,value=None):
390 def set_autoindent(self,value=None):
387 """Set the autoindent flag, checking for readline support.
391 """Set the autoindent flag, checking for readline support.
388
392
389 If called with no arguments, it acts as a toggle."""
393 If called with no arguments, it acts as a toggle."""
390
394
391 if not self.has_readline:
395 if not self.has_readline:
392 if os.name == 'posix':
396 if os.name == 'posix':
393 warn("The auto-indent feature requires the readline library")
397 warn("The auto-indent feature requires the readline library")
394 self.autoindent = 0
398 self.autoindent = 0
395 return
399 return
396 if value is None:
400 if value is None:
397 self.autoindent = not self.autoindent
401 self.autoindent = not self.autoindent
398 else:
402 else:
399 self.autoindent = value
403 self.autoindent = value
400
404
401 #-------------------------------------------------------------------------
405 #-------------------------------------------------------------------------
402 # init_* methods called by __init__
406 # init_* methods called by __init__
403 #-------------------------------------------------------------------------
407 #-------------------------------------------------------------------------
404
408
405 def init_ipython_dir(self, ipython_dir):
409 def init_ipython_dir(self, ipython_dir):
406 if ipython_dir is not None:
410 if ipython_dir is not None:
407 self.ipython_dir = ipython_dir
411 self.ipython_dir = ipython_dir
408 self.config.Global.ipython_dir = self.ipython_dir
412 self.config.Global.ipython_dir = self.ipython_dir
409 return
413 return
410
414
411 if hasattr(self.config.Global, 'ipython_dir'):
415 if hasattr(self.config.Global, 'ipython_dir'):
412 self.ipython_dir = self.config.Global.ipython_dir
416 self.ipython_dir = self.config.Global.ipython_dir
413 else:
417 else:
414 self.ipython_dir = get_ipython_dir()
418 self.ipython_dir = get_ipython_dir()
415
419
416 # All children can just read this
420 # All children can just read this
417 self.config.Global.ipython_dir = self.ipython_dir
421 self.config.Global.ipython_dir = self.ipython_dir
418
422
419 def init_instance_attrs(self):
423 def init_instance_attrs(self):
420 self.jobs = BackgroundJobManager()
424 self.jobs = BackgroundJobManager()
421 self.more = False
425 self.more = False
422
426
423 # command compiler
427 # command compiler
424 self.compile = codeop.CommandCompiler()
428 self.compile = codeop.CommandCompiler()
425
429
426 # User input buffer
430 # User input buffer
427 self.buffer = []
431 self.buffer = []
428
432
429 # Make an empty namespace, which extension writers can rely on both
433 # Make an empty namespace, which extension writers can rely on both
430 # existing and NEVER being used by ipython itself. This gives them a
434 # existing and NEVER being used by ipython itself. This gives them a
431 # convenient location for storing additional information and state
435 # convenient location for storing additional information and state
432 # their extensions may require, without fear of collisions with other
436 # their extensions may require, without fear of collisions with other
433 # ipython names that may develop later.
437 # ipython names that may develop later.
434 self.meta = Struct()
438 self.meta = Struct()
435
439
436 # Object variable to store code object waiting execution. This is
440 # Object variable to store code object waiting execution. This is
437 # used mainly by the multithreaded shells, but it can come in handy in
441 # used mainly by the multithreaded shells, but it can come in handy in
438 # other situations. No need to use a Queue here, since it's a single
442 # other situations. No need to use a Queue here, since it's a single
439 # item which gets cleared once run.
443 # item which gets cleared once run.
440 self.code_to_run = None
444 self.code_to_run = None
441
445
442 # Flag to mark unconditional exit
446 # Flag to mark unconditional exit
443 self.exit_now = False
447 self.exit_now = False
444
448
445 # Temporary files used for various purposes. Deleted at exit.
449 # Temporary files used for various purposes. Deleted at exit.
446 self.tempfiles = []
450 self.tempfiles = []
447
451
448 # Keep track of readline usage (later set by init_readline)
452 # Keep track of readline usage (later set by init_readline)
449 self.has_readline = False
453 self.has_readline = False
450
454
451 # keep track of where we started running (mainly for crash post-mortem)
455 # keep track of where we started running (mainly for crash post-mortem)
452 # This is not being used anywhere currently.
456 # This is not being used anywhere currently.
453 self.starting_dir = os.getcwd()
457 self.starting_dir = os.getcwd()
454
458
455 # Indentation management
459 # Indentation management
456 self.indent_current_nsp = 0
460 self.indent_current_nsp = 0
457
461
458 def init_term_title(self):
462 def init_term_title(self):
459 # Enable or disable the terminal title.
463 # Enable or disable the terminal title.
460 if self.term_title:
464 if self.term_title:
461 toggle_set_term_title(True)
465 toggle_set_term_title(True)
462 set_term_title('IPython: ' + abbrev_cwd())
466 set_term_title('IPython: ' + abbrev_cwd())
463 else:
467 else:
464 toggle_set_term_title(False)
468 toggle_set_term_title(False)
465
469
466 def init_usage(self, usage=None):
470 def init_usage(self, usage=None):
467 if usage is None:
471 if usage is None:
468 self.usage = interactive_usage
472 self.usage = interactive_usage
469 else:
473 else:
470 self.usage = usage
474 self.usage = usage
471
475
472 def init_encoding(self):
476 def init_encoding(self):
473 # Get system encoding at startup time. Certain terminals (like Emacs
477 # Get system encoding at startup time. Certain terminals (like Emacs
474 # under Win32 have it set to None, and we need to have a known valid
478 # under Win32 have it set to None, and we need to have a known valid
475 # encoding to use in the raw_input() method
479 # encoding to use in the raw_input() method
476 try:
480 try:
477 self.stdin_encoding = sys.stdin.encoding or 'ascii'
481 self.stdin_encoding = sys.stdin.encoding or 'ascii'
478 except AttributeError:
482 except AttributeError:
479 self.stdin_encoding = 'ascii'
483 self.stdin_encoding = 'ascii'
480
484
481 def init_syntax_highlighting(self):
485 def init_syntax_highlighting(self):
482 # Python source parser/formatter for syntax highlighting
486 # Python source parser/formatter for syntax highlighting
483 pyformat = PyColorize.Parser().format
487 pyformat = PyColorize.Parser().format
484 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
488 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
485
489
486 def init_pushd_popd_magic(self):
490 def init_pushd_popd_magic(self):
487 # for pushd/popd management
491 # for pushd/popd management
488 try:
492 try:
489 self.home_dir = get_home_dir()
493 self.home_dir = get_home_dir()
490 except HomeDirError, msg:
494 except HomeDirError, msg:
491 fatal(msg)
495 fatal(msg)
492
496
493 self.dir_stack = []
497 self.dir_stack = []
494
498
495 def init_logger(self):
499 def init_logger(self):
496 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
500 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
497 # local shortcut, this is used a LOT
501 # local shortcut, this is used a LOT
498 self.log = self.logger.log
502 self.log = self.logger.log
499
503
500 def init_logstart(self):
504 def init_logstart(self):
501 if self.logappend:
505 if self.logappend:
502 self.magic_logstart(self.logappend + ' append')
506 self.magic_logstart(self.logappend + ' append')
503 elif self.logfile:
507 elif self.logfile:
504 self.magic_logstart(self.logfile)
508 self.magic_logstart(self.logfile)
505 elif self.logstart:
509 elif self.logstart:
506 self.magic_logstart()
510 self.magic_logstart()
507
511
508 def init_builtins(self):
512 def init_builtins(self):
509 self.builtin_trap = BuiltinTrap(self)
513 self.builtin_trap = BuiltinTrap(self)
510
514
511 def init_inspector(self):
515 def init_inspector(self):
512 # Object inspector
516 # Object inspector
513 self.inspector = oinspect.Inspector(oinspect.InspectColors,
517 self.inspector = oinspect.Inspector(oinspect.InspectColors,
514 PyColorize.ANSICodeColors,
518 PyColorize.ANSICodeColors,
515 'NoColor',
519 'NoColor',
516 self.object_info_string_level)
520 self.object_info_string_level)
517
521
518 def init_prompts(self):
522 def init_prompts(self):
519 # Initialize cache, set in/out prompts and printing system
523 # Initialize cache, set in/out prompts and printing system
520 self.outputcache = CachedOutput(self,
524 self.outputcache = CachedOutput(self,
521 self.cache_size,
525 self.cache_size,
522 self.pprint,
526 self.pprint,
523 input_sep = self.separate_in,
527 input_sep = self.separate_in,
524 output_sep = self.separate_out,
528 output_sep = self.separate_out,
525 output_sep2 = self.separate_out2,
529 output_sep2 = self.separate_out2,
526 ps1 = self.prompt_in1,
530 ps1 = self.prompt_in1,
527 ps2 = self.prompt_in2,
531 ps2 = self.prompt_in2,
528 ps_out = self.prompt_out,
532 ps_out = self.prompt_out,
529 pad_left = self.prompts_pad_left)
533 pad_left = self.prompts_pad_left)
530
534
531 # user may have over-ridden the default print hook:
535 # user may have over-ridden the default print hook:
532 try:
536 try:
533 self.outputcache.__class__.display = self.hooks.display
537 self.outputcache.__class__.display = self.hooks.display
534 except AttributeError:
538 except AttributeError:
535 pass
539 pass
536
540
537 def init_displayhook(self):
541 def init_displayhook(self):
538 self.display_trap = DisplayTrap(self.outputcache)
542 self.display_trap = DisplayTrap(self.outputcache)
539
543
540 def init_reload_doctest(self):
544 def init_reload_doctest(self):
541 # Do a proper resetting of doctest, including the necessary displayhook
545 # Do a proper resetting of doctest, including the necessary displayhook
542 # monkeypatching
546 # monkeypatching
543 try:
547 try:
544 doctest_reload()
548 doctest_reload()
545 except ImportError:
549 except ImportError:
546 warn("doctest module does not exist.")
550 warn("doctest module does not exist.")
547
551
548 #-------------------------------------------------------------------------
552 #-------------------------------------------------------------------------
549 # Things related to the banner
553 # Things related to the banner
550 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
551
555
552 def init_banner(self, banner1, banner2, display_banner):
556 def init_banner(self, banner1, banner2, display_banner):
553 if banner1 is not None:
557 if banner1 is not None:
554 self.banner1 = banner1
558 self.banner1 = banner1
555 if banner2 is not None:
559 if banner2 is not None:
556 self.banner2 = banner2
560 self.banner2 = banner2
557 if display_banner is not None:
561 if display_banner is not None:
558 self.display_banner = display_banner
562 self.display_banner = display_banner
559 self.compute_banner()
563 self.compute_banner()
560
564
561 def show_banner(self, banner=None):
565 def show_banner(self, banner=None):
562 if banner is None:
566 if banner is None:
563 banner = self.banner
567 banner = self.banner
564 self.write(banner)
568 self.write(banner)
565
569
566 def compute_banner(self):
570 def compute_banner(self):
567 self.banner = self.banner1 + '\n'
571 self.banner = self.banner1 + '\n'
568 if self.profile:
572 if self.profile:
569 self.banner += '\nIPython profile: %s\n' % self.profile
573 self.banner += '\nIPython profile: %s\n' % self.profile
570 if self.banner2:
574 if self.banner2:
571 self.banner += '\n' + self.banner2 + '\n'
575 self.banner += '\n' + self.banner2 + '\n'
572
576
573 #-------------------------------------------------------------------------
577 #-------------------------------------------------------------------------
574 # Things related to injections into the sys module
578 # Things related to injections into the sys module
575 #-------------------------------------------------------------------------
579 #-------------------------------------------------------------------------
576
580
577 def save_sys_module_state(self):
581 def save_sys_module_state(self):
578 """Save the state of hooks in the sys module.
582 """Save the state of hooks in the sys module.
579
583
580 This has to be called after self.user_ns is created.
584 This has to be called after self.user_ns is created.
581 """
585 """
582 self._orig_sys_module_state = {}
586 self._orig_sys_module_state = {}
583 self._orig_sys_module_state['stdin'] = sys.stdin
587 self._orig_sys_module_state['stdin'] = sys.stdin
584 self._orig_sys_module_state['stdout'] = sys.stdout
588 self._orig_sys_module_state['stdout'] = sys.stdout
585 self._orig_sys_module_state['stderr'] = sys.stderr
589 self._orig_sys_module_state['stderr'] = sys.stderr
586 self._orig_sys_module_state['excepthook'] = sys.excepthook
590 self._orig_sys_module_state['excepthook'] = sys.excepthook
587 try:
591 try:
588 self._orig_sys_modules_main_name = self.user_ns['__name__']
592 self._orig_sys_modules_main_name = self.user_ns['__name__']
589 except KeyError:
593 except KeyError:
590 pass
594 pass
591
595
592 def restore_sys_module_state(self):
596 def restore_sys_module_state(self):
593 """Restore the state of the sys module."""
597 """Restore the state of the sys module."""
594 try:
598 try:
595 for k, v in self._orig_sys_module_state.items():
599 for k, v in self._orig_sys_module_state.items():
596 setattr(sys, k, v)
600 setattr(sys, k, v)
597 except AttributeError:
601 except AttributeError:
598 pass
602 pass
599 try:
603 try:
600 delattr(sys, 'ipcompleter')
604 delattr(sys, 'ipcompleter')
601 except AttributeError:
605 except AttributeError:
602 pass
606 pass
603 # Reset what what done in self.init_sys_modules
607 # Reset what what done in self.init_sys_modules
604 try:
608 try:
605 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
609 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
606 except (AttributeError, KeyError):
610 except (AttributeError, KeyError):
607 pass
611 pass
608
612
609 #-------------------------------------------------------------------------
613 #-------------------------------------------------------------------------
610 # Things related to hooks
614 # Things related to hooks
611 #-------------------------------------------------------------------------
615 #-------------------------------------------------------------------------
612
616
613 def init_hooks(self):
617 def init_hooks(self):
614 # hooks holds pointers used for user-side customizations
618 # hooks holds pointers used for user-side customizations
615 self.hooks = Struct()
619 self.hooks = Struct()
616
620
617 self.strdispatchers = {}
621 self.strdispatchers = {}
618
622
619 # Set all default hooks, defined in the IPython.hooks module.
623 # Set all default hooks, defined in the IPython.hooks module.
620 hooks = IPython.core.hooks
624 hooks = IPython.core.hooks
621 for hook_name in hooks.__all__:
625 for hook_name in hooks.__all__:
622 # default hooks have priority 100, i.e. low; user hooks should have
626 # default hooks have priority 100, i.e. low; user hooks should have
623 # 0-100 priority
627 # 0-100 priority
624 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
628 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
625
629
626 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
630 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
627 """set_hook(name,hook) -> sets an internal IPython hook.
631 """set_hook(name,hook) -> sets an internal IPython hook.
628
632
629 IPython exposes some of its internal API as user-modifiable hooks. By
633 IPython exposes some of its internal API as user-modifiable hooks. By
630 adding your function to one of these hooks, you can modify IPython's
634 adding your function to one of these hooks, you can modify IPython's
631 behavior to call at runtime your own routines."""
635 behavior to call at runtime your own routines."""
632
636
633 # At some point in the future, this should validate the hook before it
637 # At some point in the future, this should validate the hook before it
634 # accepts it. Probably at least check that the hook takes the number
638 # accepts it. Probably at least check that the hook takes the number
635 # of args it's supposed to.
639 # of args it's supposed to.
636
640
637 f = new.instancemethod(hook,self,self.__class__)
641 f = new.instancemethod(hook,self,self.__class__)
638
642
639 # check if the hook is for strdispatcher first
643 # check if the hook is for strdispatcher first
640 if str_key is not None:
644 if str_key is not None:
641 sdp = self.strdispatchers.get(name, StrDispatch())
645 sdp = self.strdispatchers.get(name, StrDispatch())
642 sdp.add_s(str_key, f, priority )
646 sdp.add_s(str_key, f, priority )
643 self.strdispatchers[name] = sdp
647 self.strdispatchers[name] = sdp
644 return
648 return
645 if re_key is not None:
649 if re_key is not None:
646 sdp = self.strdispatchers.get(name, StrDispatch())
650 sdp = self.strdispatchers.get(name, StrDispatch())
647 sdp.add_re(re.compile(re_key), f, priority )
651 sdp.add_re(re.compile(re_key), f, priority )
648 self.strdispatchers[name] = sdp
652 self.strdispatchers[name] = sdp
649 return
653 return
650
654
651 dp = getattr(self.hooks, name, None)
655 dp = getattr(self.hooks, name, None)
652 if name not in IPython.core.hooks.__all__:
656 if name not in IPython.core.hooks.__all__:
653 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
657 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
654 if not dp:
658 if not dp:
655 dp = IPython.core.hooks.CommandChainDispatcher()
659 dp = IPython.core.hooks.CommandChainDispatcher()
656
660
657 try:
661 try:
658 dp.add(f,priority)
662 dp.add(f,priority)
659 except AttributeError:
663 except AttributeError:
660 # it was not commandchain, plain old func - replace
664 # it was not commandchain, plain old func - replace
661 dp = f
665 dp = f
662
666
663 setattr(self.hooks,name, dp)
667 setattr(self.hooks,name, dp)
664
668
665 #-------------------------------------------------------------------------
669 #-------------------------------------------------------------------------
666 # Things related to the "main" module
670 # Things related to the "main" module
667 #-------------------------------------------------------------------------
671 #-------------------------------------------------------------------------
668
672
669 def new_main_mod(self,ns=None):
673 def new_main_mod(self,ns=None):
670 """Return a new 'main' module object for user code execution.
674 """Return a new 'main' module object for user code execution.
671 """
675 """
672 main_mod = self._user_main_module
676 main_mod = self._user_main_module
673 init_fakemod_dict(main_mod,ns)
677 init_fakemod_dict(main_mod,ns)
674 return main_mod
678 return main_mod
675
679
676 def cache_main_mod(self,ns,fname):
680 def cache_main_mod(self,ns,fname):
677 """Cache a main module's namespace.
681 """Cache a main module's namespace.
678
682
679 When scripts are executed via %run, we must keep a reference to the
683 When scripts are executed via %run, we must keep a reference to the
680 namespace of their __main__ module (a FakeModule instance) around so
684 namespace of their __main__ module (a FakeModule instance) around so
681 that Python doesn't clear it, rendering objects defined therein
685 that Python doesn't clear it, rendering objects defined therein
682 useless.
686 useless.
683
687
684 This method keeps said reference in a private dict, keyed by the
688 This method keeps said reference in a private dict, keyed by the
685 absolute path of the module object (which corresponds to the script
689 absolute path of the module object (which corresponds to the script
686 path). This way, for multiple executions of the same script we only
690 path). This way, for multiple executions of the same script we only
687 keep one copy of the namespace (the last one), thus preventing memory
691 keep one copy of the namespace (the last one), thus preventing memory
688 leaks from old references while allowing the objects from the last
692 leaks from old references while allowing the objects from the last
689 execution to be accessible.
693 execution to be accessible.
690
694
691 Note: we can not allow the actual FakeModule instances to be deleted,
695 Note: we can not allow the actual FakeModule instances to be deleted,
692 because of how Python tears down modules (it hard-sets all their
696 because of how Python tears down modules (it hard-sets all their
693 references to None without regard for reference counts). This method
697 references to None without regard for reference counts). This method
694 must therefore make a *copy* of the given namespace, to allow the
698 must therefore make a *copy* of the given namespace, to allow the
695 original module's __dict__ to be cleared and reused.
699 original module's __dict__ to be cleared and reused.
696
700
697
701
698 Parameters
702 Parameters
699 ----------
703 ----------
700 ns : a namespace (a dict, typically)
704 ns : a namespace (a dict, typically)
701
705
702 fname : str
706 fname : str
703 Filename associated with the namespace.
707 Filename associated with the namespace.
704
708
705 Examples
709 Examples
706 --------
710 --------
707
711
708 In [10]: import IPython
712 In [10]: import IPython
709
713
710 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
714 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
711
715
712 In [12]: IPython.__file__ in _ip._main_ns_cache
716 In [12]: IPython.__file__ in _ip._main_ns_cache
713 Out[12]: True
717 Out[12]: True
714 """
718 """
715 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
719 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
716
720
717 def clear_main_mod_cache(self):
721 def clear_main_mod_cache(self):
718 """Clear the cache of main modules.
722 """Clear the cache of main modules.
719
723
720 Mainly for use by utilities like %reset.
724 Mainly for use by utilities like %reset.
721
725
722 Examples
726 Examples
723 --------
727 --------
724
728
725 In [15]: import IPython
729 In [15]: import IPython
726
730
727 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
731 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
728
732
729 In [17]: len(_ip._main_ns_cache) > 0
733 In [17]: len(_ip._main_ns_cache) > 0
730 Out[17]: True
734 Out[17]: True
731
735
732 In [18]: _ip.clear_main_mod_cache()
736 In [18]: _ip.clear_main_mod_cache()
733
737
734 In [19]: len(_ip._main_ns_cache) == 0
738 In [19]: len(_ip._main_ns_cache) == 0
735 Out[19]: True
739 Out[19]: True
736 """
740 """
737 self._main_ns_cache.clear()
741 self._main_ns_cache.clear()
738
742
739 #-------------------------------------------------------------------------
743 #-------------------------------------------------------------------------
740 # Things related to debugging
744 # Things related to debugging
741 #-------------------------------------------------------------------------
745 #-------------------------------------------------------------------------
742
746
743 def init_pdb(self):
747 def init_pdb(self):
744 # Set calling of pdb on exceptions
748 # Set calling of pdb on exceptions
745 # self.call_pdb is a property
749 # self.call_pdb is a property
746 self.call_pdb = self.pdb
750 self.call_pdb = self.pdb
747
751
748 def _get_call_pdb(self):
752 def _get_call_pdb(self):
749 return self._call_pdb
753 return self._call_pdb
750
754
751 def _set_call_pdb(self,val):
755 def _set_call_pdb(self,val):
752
756
753 if val not in (0,1,False,True):
757 if val not in (0,1,False,True):
754 raise ValueError,'new call_pdb value must be boolean'
758 raise ValueError,'new call_pdb value must be boolean'
755
759
756 # store value in instance
760 # store value in instance
757 self._call_pdb = val
761 self._call_pdb = val
758
762
759 # notify the actual exception handlers
763 # notify the actual exception handlers
760 self.InteractiveTB.call_pdb = val
764 self.InteractiveTB.call_pdb = val
761 if self.isthreaded:
765 if self.isthreaded:
762 try:
766 try:
763 self.sys_excepthook.call_pdb = val
767 self.sys_excepthook.call_pdb = val
764 except:
768 except:
765 warn('Failed to activate pdb for threaded exception handler')
769 warn('Failed to activate pdb for threaded exception handler')
766
770
767 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
771 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
768 'Control auto-activation of pdb at exceptions')
772 'Control auto-activation of pdb at exceptions')
769
773
770 def debugger(self,force=False):
774 def debugger(self,force=False):
771 """Call the pydb/pdb debugger.
775 """Call the pydb/pdb debugger.
772
776
773 Keywords:
777 Keywords:
774
778
775 - force(False): by default, this routine checks the instance call_pdb
779 - force(False): by default, this routine checks the instance call_pdb
776 flag and does not actually invoke the debugger if the flag is false.
780 flag and does not actually invoke the debugger if the flag is false.
777 The 'force' option forces the debugger to activate even if the flag
781 The 'force' option forces the debugger to activate even if the flag
778 is false.
782 is false.
779 """
783 """
780
784
781 if not (force or self.call_pdb):
785 if not (force or self.call_pdb):
782 return
786 return
783
787
784 if not hasattr(sys,'last_traceback'):
788 if not hasattr(sys,'last_traceback'):
785 error('No traceback has been produced, nothing to debug.')
789 error('No traceback has been produced, nothing to debug.')
786 return
790 return
787
791
788 # use pydb if available
792 # use pydb if available
789 if debugger.has_pydb:
793 if debugger.has_pydb:
790 from pydb import pm
794 from pydb import pm
791 else:
795 else:
792 # fallback to our internal debugger
796 # fallback to our internal debugger
793 pm = lambda : self.InteractiveTB.debugger(force=True)
797 pm = lambda : self.InteractiveTB.debugger(force=True)
794 self.history_saving_wrapper(pm)()
798 self.history_saving_wrapper(pm)()
795
799
796 #-------------------------------------------------------------------------
800 #-------------------------------------------------------------------------
797 # Things related to IPython's various namespaces
801 # Things related to IPython's various namespaces
798 #-------------------------------------------------------------------------
802 #-------------------------------------------------------------------------
799
803
800 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
804 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
801 # Create the namespace where the user will operate. user_ns is
805 # Create the namespace where the user will operate. user_ns is
802 # normally the only one used, and it is passed to the exec calls as
806 # normally the only one used, and it is passed to the exec calls as
803 # the locals argument. But we do carry a user_global_ns namespace
807 # the locals argument. But we do carry a user_global_ns namespace
804 # given as the exec 'globals' argument, This is useful in embedding
808 # given as the exec 'globals' argument, This is useful in embedding
805 # situations where the ipython shell opens in a context where the
809 # situations where the ipython shell opens in a context where the
806 # distinction between locals and globals is meaningful. For
810 # distinction between locals and globals is meaningful. For
807 # non-embedded contexts, it is just the same object as the user_ns dict.
811 # non-embedded contexts, it is just the same object as the user_ns dict.
808
812
809 # FIXME. For some strange reason, __builtins__ is showing up at user
813 # FIXME. For some strange reason, __builtins__ is showing up at user
810 # level as a dict instead of a module. This is a manual fix, but I
814 # level as a dict instead of a module. This is a manual fix, but I
811 # should really track down where the problem is coming from. Alex
815 # should really track down where the problem is coming from. Alex
812 # Schmolck reported this problem first.
816 # Schmolck reported this problem first.
813
817
814 # A useful post by Alex Martelli on this topic:
818 # A useful post by Alex Martelli on this topic:
815 # Re: inconsistent value from __builtins__
819 # Re: inconsistent value from __builtins__
816 # Von: Alex Martelli <aleaxit@yahoo.com>
820 # Von: Alex Martelli <aleaxit@yahoo.com>
817 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
821 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
818 # Gruppen: comp.lang.python
822 # Gruppen: comp.lang.python
819
823
820 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
824 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
821 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
825 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
822 # > <type 'dict'>
826 # > <type 'dict'>
823 # > >>> print type(__builtins__)
827 # > >>> print type(__builtins__)
824 # > <type 'module'>
828 # > <type 'module'>
825 # > Is this difference in return value intentional?
829 # > Is this difference in return value intentional?
826
830
827 # Well, it's documented that '__builtins__' can be either a dictionary
831 # Well, it's documented that '__builtins__' can be either a dictionary
828 # or a module, and it's been that way for a long time. Whether it's
832 # or a module, and it's been that way for a long time. Whether it's
829 # intentional (or sensible), I don't know. In any case, the idea is
833 # intentional (or sensible), I don't know. In any case, the idea is
830 # that if you need to access the built-in namespace directly, you
834 # that if you need to access the built-in namespace directly, you
831 # should start with "import __builtin__" (note, no 's') which will
835 # should start with "import __builtin__" (note, no 's') which will
832 # definitely give you a module. Yeah, it's somewhat confusing:-(.
836 # definitely give you a module. Yeah, it's somewhat confusing:-(.
833
837
834 # These routines return properly built dicts as needed by the rest of
838 # These routines return properly built dicts as needed by the rest of
835 # the code, and can also be used by extension writers to generate
839 # the code, and can also be used by extension writers to generate
836 # properly initialized namespaces.
840 # properly initialized namespaces.
837 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
841 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
838
842
839 # Assign namespaces
843 # Assign namespaces
840 # This is the namespace where all normal user variables live
844 # This is the namespace where all normal user variables live
841 self.user_ns = user_ns
845 self.user_ns = user_ns
842 self.user_global_ns = user_global_ns
846 self.user_global_ns = user_global_ns
843
847
844 # An auxiliary namespace that checks what parts of the user_ns were
848 # An auxiliary namespace that checks what parts of the user_ns were
845 # loaded at startup, so we can list later only variables defined in
849 # loaded at startup, so we can list later only variables defined in
846 # actual interactive use. Since it is always a subset of user_ns, it
850 # actual interactive use. Since it is always a subset of user_ns, it
847 # doesn't need to be separately tracked in the ns_table.
851 # doesn't need to be separately tracked in the ns_table.
848 self.user_ns_hidden = {}
852 self.user_ns_hidden = {}
849
853
850 # A namespace to keep track of internal data structures to prevent
854 # A namespace to keep track of internal data structures to prevent
851 # them from cluttering user-visible stuff. Will be updated later
855 # them from cluttering user-visible stuff. Will be updated later
852 self.internal_ns = {}
856 self.internal_ns = {}
853
857
854 # Now that FakeModule produces a real module, we've run into a nasty
858 # Now that FakeModule produces a real module, we've run into a nasty
855 # problem: after script execution (via %run), the module where the user
859 # problem: after script execution (via %run), the module where the user
856 # code ran is deleted. Now that this object is a true module (needed
860 # code ran is deleted. Now that this object is a true module (needed
857 # so docetst and other tools work correctly), the Python module
861 # so docetst and other tools work correctly), the Python module
858 # teardown mechanism runs over it, and sets to None every variable
862 # teardown mechanism runs over it, and sets to None every variable
859 # present in that module. Top-level references to objects from the
863 # present in that module. Top-level references to objects from the
860 # script survive, because the user_ns is updated with them. However,
864 # script survive, because the user_ns is updated with them. However,
861 # calling functions defined in the script that use other things from
865 # calling functions defined in the script that use other things from
862 # the script will fail, because the function's closure had references
866 # the script will fail, because the function's closure had references
863 # to the original objects, which are now all None. So we must protect
867 # to the original objects, which are now all None. So we must protect
864 # these modules from deletion by keeping a cache.
868 # these modules from deletion by keeping a cache.
865 #
869 #
866 # To avoid keeping stale modules around (we only need the one from the
870 # To avoid keeping stale modules around (we only need the one from the
867 # last run), we use a dict keyed with the full path to the script, so
871 # last run), we use a dict keyed with the full path to the script, so
868 # only the last version of the module is held in the cache. Note,
872 # only the last version of the module is held in the cache. Note,
869 # however, that we must cache the module *namespace contents* (their
873 # however, that we must cache the module *namespace contents* (their
870 # __dict__). Because if we try to cache the actual modules, old ones
874 # __dict__). Because if we try to cache the actual modules, old ones
871 # (uncached) could be destroyed while still holding references (such as
875 # (uncached) could be destroyed while still holding references (such as
872 # those held by GUI objects that tend to be long-lived)>
876 # those held by GUI objects that tend to be long-lived)>
873 #
877 #
874 # The %reset command will flush this cache. See the cache_main_mod()
878 # The %reset command will flush this cache. See the cache_main_mod()
875 # and clear_main_mod_cache() methods for details on use.
879 # and clear_main_mod_cache() methods for details on use.
876
880
877 # This is the cache used for 'main' namespaces
881 # This is the cache used for 'main' namespaces
878 self._main_ns_cache = {}
882 self._main_ns_cache = {}
879 # And this is the single instance of FakeModule whose __dict__ we keep
883 # And this is the single instance of FakeModule whose __dict__ we keep
880 # copying and clearing for reuse on each %run
884 # copying and clearing for reuse on each %run
881 self._user_main_module = FakeModule()
885 self._user_main_module = FakeModule()
882
886
883 # A table holding all the namespaces IPython deals with, so that
887 # A table holding all the namespaces IPython deals with, so that
884 # introspection facilities can search easily.
888 # introspection facilities can search easily.
885 self.ns_table = {'user':user_ns,
889 self.ns_table = {'user':user_ns,
886 'user_global':user_global_ns,
890 'user_global':user_global_ns,
887 'internal':self.internal_ns,
891 'internal':self.internal_ns,
888 'builtin':__builtin__.__dict__
892 'builtin':__builtin__.__dict__
889 }
893 }
890
894
891 # Similarly, track all namespaces where references can be held and that
895 # Similarly, track all namespaces where references can be held and that
892 # we can safely clear (so it can NOT include builtin). This one can be
896 # we can safely clear (so it can NOT include builtin). This one can be
893 # a simple list.
897 # a simple list.
894 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
898 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
895 self.internal_ns, self._main_ns_cache ]
899 self.internal_ns, self._main_ns_cache ]
896
900
897 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
901 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
898 """Return a valid local and global user interactive namespaces.
902 """Return a valid local and global user interactive namespaces.
899
903
900 This builds a dict with the minimal information needed to operate as a
904 This builds a dict with the minimal information needed to operate as a
901 valid IPython user namespace, which you can pass to the various
905 valid IPython user namespace, which you can pass to the various
902 embedding classes in ipython. The default implementation returns the
906 embedding classes in ipython. The default implementation returns the
903 same dict for both the locals and the globals to allow functions to
907 same dict for both the locals and the globals to allow functions to
904 refer to variables in the namespace. Customized implementations can
908 refer to variables in the namespace. Customized implementations can
905 return different dicts. The locals dictionary can actually be anything
909 return different dicts. The locals dictionary can actually be anything
906 following the basic mapping protocol of a dict, but the globals dict
910 following the basic mapping protocol of a dict, but the globals dict
907 must be a true dict, not even a subclass. It is recommended that any
911 must be a true dict, not even a subclass. It is recommended that any
908 custom object for the locals namespace synchronize with the globals
912 custom object for the locals namespace synchronize with the globals
909 dict somehow.
913 dict somehow.
910
914
911 Raises TypeError if the provided globals namespace is not a true dict.
915 Raises TypeError if the provided globals namespace is not a true dict.
912
916
913 Parameters
917 Parameters
914 ----------
918 ----------
915 user_ns : dict-like, optional
919 user_ns : dict-like, optional
916 The current user namespace. The items in this namespace should
920 The current user namespace. The items in this namespace should
917 be included in the output. If None, an appropriate blank
921 be included in the output. If None, an appropriate blank
918 namespace should be created.
922 namespace should be created.
919 user_global_ns : dict, optional
923 user_global_ns : dict, optional
920 The current user global namespace. The items in this namespace
924 The current user global namespace. The items in this namespace
921 should be included in the output. If None, an appropriate
925 should be included in the output. If None, an appropriate
922 blank namespace should be created.
926 blank namespace should be created.
923
927
924 Returns
928 Returns
925 -------
929 -------
926 A pair of dictionary-like object to be used as the local namespace
930 A pair of dictionary-like object to be used as the local namespace
927 of the interpreter and a dict to be used as the global namespace.
931 of the interpreter and a dict to be used as the global namespace.
928 """
932 """
929
933
930
934
931 # We must ensure that __builtin__ (without the final 's') is always
935 # We must ensure that __builtin__ (without the final 's') is always
932 # available and pointing to the __builtin__ *module*. For more details:
936 # available and pointing to the __builtin__ *module*. For more details:
933 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
937 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
934
938
935 if user_ns is None:
939 if user_ns is None:
936 # Set __name__ to __main__ to better match the behavior of the
940 # Set __name__ to __main__ to better match the behavior of the
937 # normal interpreter.
941 # normal interpreter.
938 user_ns = {'__name__' :'__main__',
942 user_ns = {'__name__' :'__main__',
939 '__builtin__' : __builtin__,
943 '__builtin__' : __builtin__,
940 '__builtins__' : __builtin__,
944 '__builtins__' : __builtin__,
941 }
945 }
942 else:
946 else:
943 user_ns.setdefault('__name__','__main__')
947 user_ns.setdefault('__name__','__main__')
944 user_ns.setdefault('__builtin__',__builtin__)
948 user_ns.setdefault('__builtin__',__builtin__)
945 user_ns.setdefault('__builtins__',__builtin__)
949 user_ns.setdefault('__builtins__',__builtin__)
946
950
947 if user_global_ns is None:
951 if user_global_ns is None:
948 user_global_ns = user_ns
952 user_global_ns = user_ns
949 if type(user_global_ns) is not dict:
953 if type(user_global_ns) is not dict:
950 raise TypeError("user_global_ns must be a true dict; got %r"
954 raise TypeError("user_global_ns must be a true dict; got %r"
951 % type(user_global_ns))
955 % type(user_global_ns))
952
956
953 return user_ns, user_global_ns
957 return user_ns, user_global_ns
954
958
955 def init_sys_modules(self):
959 def init_sys_modules(self):
956 # We need to insert into sys.modules something that looks like a
960 # We need to insert into sys.modules something that looks like a
957 # module but which accesses the IPython namespace, for shelve and
961 # module but which accesses the IPython namespace, for shelve and
958 # pickle to work interactively. Normally they rely on getting
962 # pickle to work interactively. Normally they rely on getting
959 # everything out of __main__, but for embedding purposes each IPython
963 # everything out of __main__, but for embedding purposes each IPython
960 # instance has its own private namespace, so we can't go shoving
964 # instance has its own private namespace, so we can't go shoving
961 # everything into __main__.
965 # everything into __main__.
962
966
963 # note, however, that we should only do this for non-embedded
967 # note, however, that we should only do this for non-embedded
964 # ipythons, which really mimic the __main__.__dict__ with their own
968 # ipythons, which really mimic the __main__.__dict__ with their own
965 # namespace. Embedded instances, on the other hand, should not do
969 # namespace. Embedded instances, on the other hand, should not do
966 # this because they need to manage the user local/global namespaces
970 # this because they need to manage the user local/global namespaces
967 # only, but they live within a 'normal' __main__ (meaning, they
971 # only, but they live within a 'normal' __main__ (meaning, they
968 # shouldn't overtake the execution environment of the script they're
972 # shouldn't overtake the execution environment of the script they're
969 # embedded in).
973 # embedded in).
970
974
971 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
975 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
972
976
973 try:
977 try:
974 main_name = self.user_ns['__name__']
978 main_name = self.user_ns['__name__']
975 except KeyError:
979 except KeyError:
976 raise KeyError('user_ns dictionary MUST have a "__name__" key')
980 raise KeyError('user_ns dictionary MUST have a "__name__" key')
977 else:
981 else:
978 sys.modules[main_name] = FakeModule(self.user_ns)
982 sys.modules[main_name] = FakeModule(self.user_ns)
979
983
980 def init_user_ns(self):
984 def init_user_ns(self):
981 """Initialize all user-visible namespaces to their minimum defaults.
985 """Initialize all user-visible namespaces to their minimum defaults.
982
986
983 Certain history lists are also initialized here, as they effectively
987 Certain history lists are also initialized here, as they effectively
984 act as user namespaces.
988 act as user namespaces.
985
989
986 Notes
990 Notes
987 -----
991 -----
988 All data structures here are only filled in, they are NOT reset by this
992 All data structures here are only filled in, they are NOT reset by this
989 method. If they were not empty before, data will simply be added to
993 method. If they were not empty before, data will simply be added to
990 therm.
994 therm.
991 """
995 """
992 # This function works in two parts: first we put a few things in
996 # This function works in two parts: first we put a few things in
993 # user_ns, and we sync that contents into user_ns_hidden so that these
997 # user_ns, and we sync that contents into user_ns_hidden so that these
994 # initial variables aren't shown by %who. After the sync, we add the
998 # initial variables aren't shown by %who. After the sync, we add the
995 # rest of what we *do* want the user to see with %who even on a new
999 # rest of what we *do* want the user to see with %who even on a new
996 # session (probably nothing, so theye really only see their own stuff)
1000 # session (probably nothing, so theye really only see their own stuff)
997
1001
998 # The user dict must *always* have a __builtin__ reference to the
1002 # The user dict must *always* have a __builtin__ reference to the
999 # Python standard __builtin__ namespace, which must be imported.
1003 # Python standard __builtin__ namespace, which must be imported.
1000 # This is so that certain operations in prompt evaluation can be
1004 # This is so that certain operations in prompt evaluation can be
1001 # reliably executed with builtins. Note that we can NOT use
1005 # reliably executed with builtins. Note that we can NOT use
1002 # __builtins__ (note the 's'), because that can either be a dict or a
1006 # __builtins__ (note the 's'), because that can either be a dict or a
1003 # module, and can even mutate at runtime, depending on the context
1007 # module, and can even mutate at runtime, depending on the context
1004 # (Python makes no guarantees on it). In contrast, __builtin__ is
1008 # (Python makes no guarantees on it). In contrast, __builtin__ is
1005 # always a module object, though it must be explicitly imported.
1009 # always a module object, though it must be explicitly imported.
1006
1010
1007 # For more details:
1011 # For more details:
1008 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1012 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1009 ns = dict(__builtin__ = __builtin__)
1013 ns = dict(__builtin__ = __builtin__)
1010
1014
1011 # Put 'help' in the user namespace
1015 # Put 'help' in the user namespace
1012 try:
1016 try:
1013 from site import _Helper
1017 from site import _Helper
1014 ns['help'] = _Helper()
1018 ns['help'] = _Helper()
1015 except ImportError:
1019 except ImportError:
1016 warn('help() not available - check site.py')
1020 warn('help() not available - check site.py')
1017
1021
1018 # make global variables for user access to the histories
1022 # make global variables for user access to the histories
1019 ns['_ih'] = self.input_hist
1023 ns['_ih'] = self.input_hist
1020 ns['_oh'] = self.output_hist
1024 ns['_oh'] = self.output_hist
1021 ns['_dh'] = self.dir_hist
1025 ns['_dh'] = self.dir_hist
1022
1026
1023 ns['_sh'] = shadowns
1027 ns['_sh'] = shadowns
1024
1028
1025 # user aliases to input and output histories. These shouldn't show up
1029 # user aliases to input and output histories. These shouldn't show up
1026 # in %who, as they can have very large reprs.
1030 # in %who, as they can have very large reprs.
1027 ns['In'] = self.input_hist
1031 ns['In'] = self.input_hist
1028 ns['Out'] = self.output_hist
1032 ns['Out'] = self.output_hist
1029
1033
1030 # Store myself as the public api!!!
1034 # Store myself as the public api!!!
1031 ns['get_ipython'] = self.get_ipython
1035 ns['get_ipython'] = self.get_ipython
1032
1036
1033 # Sync what we've added so far to user_ns_hidden so these aren't seen
1037 # Sync what we've added so far to user_ns_hidden so these aren't seen
1034 # by %who
1038 # by %who
1035 self.user_ns_hidden.update(ns)
1039 self.user_ns_hidden.update(ns)
1036
1040
1037 # Anything put into ns now would show up in %who. Think twice before
1041 # Anything put into ns now would show up in %who. Think twice before
1038 # putting anything here, as we really want %who to show the user their
1042 # putting anything here, as we really want %who to show the user their
1039 # stuff, not our variables.
1043 # stuff, not our variables.
1040
1044
1041 # Finally, update the real user's namespace
1045 # Finally, update the real user's namespace
1042 self.user_ns.update(ns)
1046 self.user_ns.update(ns)
1043
1047
1044
1048
1045 def reset(self):
1049 def reset(self):
1046 """Clear all internal namespaces.
1050 """Clear all internal namespaces.
1047
1051
1048 Note that this is much more aggressive than %reset, since it clears
1052 Note that this is much more aggressive than %reset, since it clears
1049 fully all namespaces, as well as all input/output lists.
1053 fully all namespaces, as well as all input/output lists.
1050 """
1054 """
1051 for ns in self.ns_refs_table:
1055 for ns in self.ns_refs_table:
1052 ns.clear()
1056 ns.clear()
1053
1057
1054 self.alias_manager.clear_aliases()
1058 self.alias_manager.clear_aliases()
1055
1059
1056 # Clear input and output histories
1060 # Clear input and output histories
1057 self.input_hist[:] = []
1061 self.input_hist[:] = []
1058 self.input_hist_raw[:] = []
1062 self.input_hist_raw[:] = []
1059 self.output_hist.clear()
1063 self.output_hist.clear()
1060
1064
1061 # Restore the user namespaces to minimal usability
1065 # Restore the user namespaces to minimal usability
1062 self.init_user_ns()
1066 self.init_user_ns()
1063
1067
1064 # Restore the default and user aliases
1068 # Restore the default and user aliases
1065 self.alias_manager.init_aliases()
1069 self.alias_manager.init_aliases()
1066
1070
1067 def reset_selective(self, regex=None):
1071 def reset_selective(self, regex=None):
1068 """Clear selective variables from internal namespaces based on a specified regular expression.
1072 """Clear selective variables from internal namespaces based on a specified regular expression.
1069
1073
1070 Parameters
1074 Parameters
1071 ----------
1075 ----------
1072 regex : string or compiled pattern, optional
1076 regex : string or compiled pattern, optional
1073 A regular expression pattern that will be used in searching variable names in the users
1077 A regular expression pattern that will be used in searching variable names in the users
1074 namespaces.
1078 namespaces.
1075 """
1079 """
1076 if regex is not None:
1080 if regex is not None:
1077 try:
1081 try:
1078 m = re.compile(regex)
1082 m = re.compile(regex)
1079 except TypeError:
1083 except TypeError:
1080 raise TypeError('regex must be a string or compiled pattern')
1084 raise TypeError('regex must be a string or compiled pattern')
1081 # Search for keys in each namespace that match the given regex
1085 # Search for keys in each namespace that match the given regex
1082 # If a match is found, delete the key/value pair.
1086 # If a match is found, delete the key/value pair.
1083 for ns in self.ns_refs_table:
1087 for ns in self.ns_refs_table:
1084 for var in ns:
1088 for var in ns:
1085 if m.search(var):
1089 if m.search(var):
1086 del ns[var]
1090 del ns[var]
1087
1091
1088 def push(self, variables, interactive=True):
1092 def push(self, variables, interactive=True):
1089 """Inject a group of variables into the IPython user namespace.
1093 """Inject a group of variables into the IPython user namespace.
1090
1094
1091 Parameters
1095 Parameters
1092 ----------
1096 ----------
1093 variables : dict, str or list/tuple of str
1097 variables : dict, str or list/tuple of str
1094 The variables to inject into the user's namespace. If a dict,
1098 The variables to inject into the user's namespace. If a dict,
1095 a simple update is done. If a str, the string is assumed to
1099 a simple update is done. If a str, the string is assumed to
1096 have variable names separated by spaces. A list/tuple of str
1100 have variable names separated by spaces. A list/tuple of str
1097 can also be used to give the variable names. If just the variable
1101 can also be used to give the variable names. If just the variable
1098 names are give (list/tuple/str) then the variable values looked
1102 names are give (list/tuple/str) then the variable values looked
1099 up in the callers frame.
1103 up in the callers frame.
1100 interactive : bool
1104 interactive : bool
1101 If True (default), the variables will be listed with the ``who``
1105 If True (default), the variables will be listed with the ``who``
1102 magic.
1106 magic.
1103 """
1107 """
1104 vdict = None
1108 vdict = None
1105
1109
1106 # We need a dict of name/value pairs to do namespace updates.
1110 # We need a dict of name/value pairs to do namespace updates.
1107 if isinstance(variables, dict):
1111 if isinstance(variables, dict):
1108 vdict = variables
1112 vdict = variables
1109 elif isinstance(variables, (basestring, list, tuple)):
1113 elif isinstance(variables, (basestring, list, tuple)):
1110 if isinstance(variables, basestring):
1114 if isinstance(variables, basestring):
1111 vlist = variables.split()
1115 vlist = variables.split()
1112 else:
1116 else:
1113 vlist = variables
1117 vlist = variables
1114 vdict = {}
1118 vdict = {}
1115 cf = sys._getframe(1)
1119 cf = sys._getframe(1)
1116 for name in vlist:
1120 for name in vlist:
1117 try:
1121 try:
1118 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1122 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1119 except:
1123 except:
1120 print ('Could not get variable %s from %s' %
1124 print ('Could not get variable %s from %s' %
1121 (name,cf.f_code.co_name))
1125 (name,cf.f_code.co_name))
1122 else:
1126 else:
1123 raise ValueError('variables must be a dict/str/list/tuple')
1127 raise ValueError('variables must be a dict/str/list/tuple')
1124
1128
1125 # Propagate variables to user namespace
1129 # Propagate variables to user namespace
1126 self.user_ns.update(vdict)
1130 self.user_ns.update(vdict)
1127
1131
1128 # And configure interactive visibility
1132 # And configure interactive visibility
1129 config_ns = self.user_ns_hidden
1133 config_ns = self.user_ns_hidden
1130 if interactive:
1134 if interactive:
1131 for name, val in vdict.iteritems():
1135 for name, val in vdict.iteritems():
1132 config_ns.pop(name, None)
1136 config_ns.pop(name, None)
1133 else:
1137 else:
1134 for name,val in vdict.iteritems():
1138 for name,val in vdict.iteritems():
1135 config_ns[name] = val
1139 config_ns[name] = val
1136
1140
1137 #-------------------------------------------------------------------------
1141 #-------------------------------------------------------------------------
1138 # Things related to history management
1142 # Things related to history management
1139 #-------------------------------------------------------------------------
1143 #-------------------------------------------------------------------------
1140
1144
1141 def init_history(self):
1145 def init_history(self):
1142 # List of input with multi-line handling.
1146 # List of input with multi-line handling.
1143 self.input_hist = InputList()
1147 self.input_hist = InputList()
1144 # This one will hold the 'raw' input history, without any
1148 # This one will hold the 'raw' input history, without any
1145 # pre-processing. This will allow users to retrieve the input just as
1149 # pre-processing. This will allow users to retrieve the input just as
1146 # it was exactly typed in by the user, with %hist -r.
1150 # it was exactly typed in by the user, with %hist -r.
1147 self.input_hist_raw = InputList()
1151 self.input_hist_raw = InputList()
1148
1152
1149 # list of visited directories
1153 # list of visited directories
1150 try:
1154 try:
1151 self.dir_hist = [os.getcwd()]
1155 self.dir_hist = [os.getcwd()]
1152 except OSError:
1156 except OSError:
1153 self.dir_hist = []
1157 self.dir_hist = []
1154
1158
1155 # dict of output history
1159 # dict of output history
1156 self.output_hist = {}
1160 self.output_hist = {}
1157
1161
1158 # Now the history file
1162 # Now the history file
1159 if self.profile:
1163 if self.profile:
1160 histfname = 'history-%s' % self.profile
1164 histfname = 'history-%s' % self.profile
1161 else:
1165 else:
1162 histfname = 'history'
1166 histfname = 'history'
1163 self.histfile = os.path.join(self.ipython_dir, histfname)
1167 self.histfile = os.path.join(self.ipython_dir, histfname)
1164
1168
1165 # Fill the history zero entry, user counter starts at 1
1169 # Fill the history zero entry, user counter starts at 1
1166 self.input_hist.append('\n')
1170 self.input_hist.append('\n')
1167 self.input_hist_raw.append('\n')
1171 self.input_hist_raw.append('\n')
1168
1172
1169 def init_shadow_hist(self):
1173 def init_shadow_hist(self):
1170 try:
1174 try:
1171 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1175 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1172 except exceptions.UnicodeDecodeError:
1176 except exceptions.UnicodeDecodeError:
1173 print "Your ipython_dir can't be decoded to unicode!"
1177 print "Your ipython_dir can't be decoded to unicode!"
1174 print "Please set HOME environment variable to something that"
1178 print "Please set HOME environment variable to something that"
1175 print r"only has ASCII characters, e.g. c:\home"
1179 print r"only has ASCII characters, e.g. c:\home"
1176 print "Now it is", self.ipython_dir
1180 print "Now it is", self.ipython_dir
1177 sys.exit()
1181 sys.exit()
1178 self.shadowhist = ipcorehist.ShadowHist(self.db)
1182 self.shadowhist = ipcorehist.ShadowHist(self.db)
1179
1183
1180 def savehist(self):
1184 def savehist(self):
1181 """Save input history to a file (via readline library)."""
1185 """Save input history to a file (via readline library)."""
1182
1186
1183 try:
1187 try:
1184 self.readline.write_history_file(self.histfile)
1188 self.readline.write_history_file(self.histfile)
1185 except:
1189 except:
1186 print 'Unable to save IPython command history to file: ' + \
1190 print 'Unable to save IPython command history to file: ' + \
1187 `self.histfile`
1191 `self.histfile`
1188
1192
1189 def reloadhist(self):
1193 def reloadhist(self):
1190 """Reload the input history from disk file."""
1194 """Reload the input history from disk file."""
1191
1195
1192 try:
1196 try:
1193 self.readline.clear_history()
1197 self.readline.clear_history()
1194 self.readline.read_history_file(self.shell.histfile)
1198 self.readline.read_history_file(self.shell.histfile)
1195 except AttributeError:
1199 except AttributeError:
1196 pass
1200 pass
1197
1201
1198 def history_saving_wrapper(self, func):
1202 def history_saving_wrapper(self, func):
1199 """ Wrap func for readline history saving
1203 """ Wrap func for readline history saving
1200
1204
1201 Convert func into callable that saves & restores
1205 Convert func into callable that saves & restores
1202 history around the call """
1206 history around the call """
1203
1207
1204 if self.has_readline:
1208 if self.has_readline:
1205 from IPython.utils import rlineimpl as readline
1209 from IPython.utils import rlineimpl as readline
1206 else:
1210 else:
1207 return func
1211 return func
1208
1212
1209 def wrapper():
1213 def wrapper():
1210 self.savehist()
1214 self.savehist()
1211 try:
1215 try:
1212 func()
1216 func()
1213 finally:
1217 finally:
1214 readline.read_history_file(self.histfile)
1218 readline.read_history_file(self.histfile)
1215 return wrapper
1219 return wrapper
1216
1220
1217 #-------------------------------------------------------------------------
1221 #-------------------------------------------------------------------------
1218 # Things related to exception handling and tracebacks (not debugging)
1222 # Things related to exception handling and tracebacks (not debugging)
1219 #-------------------------------------------------------------------------
1223 #-------------------------------------------------------------------------
1220
1224
1221 def init_traceback_handlers(self, custom_exceptions):
1225 def init_traceback_handlers(self, custom_exceptions):
1222 # Syntax error handler.
1226 # Syntax error handler.
1223 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1227 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1224
1228
1225 # The interactive one is initialized with an offset, meaning we always
1229 # The interactive one is initialized with an offset, meaning we always
1226 # want to remove the topmost item in the traceback, which is our own
1230 # want to remove the topmost item in the traceback, which is our own
1227 # internal code. Valid modes: ['Plain','Context','Verbose']
1231 # internal code. Valid modes: ['Plain','Context','Verbose']
1228 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1232 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1229 color_scheme='NoColor',
1233 color_scheme='NoColor',
1230 tb_offset = 1)
1234 tb_offset = 1)
1231
1235
1232 # The instance will store a pointer to the system-wide exception hook,
1236 # The instance will store a pointer to the system-wide exception hook,
1233 # so that runtime code (such as magics) can access it. This is because
1237 # so that runtime code (such as magics) can access it. This is because
1234 # during the read-eval loop, it may get temporarily overwritten.
1238 # during the read-eval loop, it may get temporarily overwritten.
1235 self.sys_excepthook = sys.excepthook
1239 self.sys_excepthook = sys.excepthook
1236
1240
1237 # and add any custom exception handlers the user may have specified
1241 # and add any custom exception handlers the user may have specified
1238 self.set_custom_exc(*custom_exceptions)
1242 self.set_custom_exc(*custom_exceptions)
1239
1243
1240 # Set the exception mode
1244 # Set the exception mode
1241 self.InteractiveTB.set_mode(mode=self.xmode)
1245 self.InteractiveTB.set_mode(mode=self.xmode)
1242
1246
1243 def set_custom_exc(self,exc_tuple,handler):
1247 def set_custom_exc(self,exc_tuple,handler):
1244 """set_custom_exc(exc_tuple,handler)
1248 """set_custom_exc(exc_tuple,handler)
1245
1249
1246 Set a custom exception handler, which will be called if any of the
1250 Set a custom exception handler, which will be called if any of the
1247 exceptions in exc_tuple occur in the mainloop (specifically, in the
1251 exceptions in exc_tuple occur in the mainloop (specifically, in the
1248 runcode() method.
1252 runcode() method.
1249
1253
1250 Inputs:
1254 Inputs:
1251
1255
1252 - exc_tuple: a *tuple* of valid exceptions to call the defined
1256 - exc_tuple: a *tuple* of valid exceptions to call the defined
1253 handler for. It is very important that you use a tuple, and NOT A
1257 handler for. It is very important that you use a tuple, and NOT A
1254 LIST here, because of the way Python's except statement works. If
1258 LIST here, because of the way Python's except statement works. If
1255 you only want to trap a single exception, use a singleton tuple:
1259 you only want to trap a single exception, use a singleton tuple:
1256
1260
1257 exc_tuple == (MyCustomException,)
1261 exc_tuple == (MyCustomException,)
1258
1262
1259 - handler: this must be defined as a function with the following
1263 - handler: this must be defined as a function with the following
1260 basic interface: def my_handler(self,etype,value,tb).
1264 basic interface: def my_handler(self,etype,value,tb).
1261
1265
1262 This will be made into an instance method (via new.instancemethod)
1266 This will be made into an instance method (via new.instancemethod)
1263 of IPython itself, and it will be called if any of the exceptions
1267 of IPython itself, and it will be called if any of the exceptions
1264 listed in the exc_tuple are caught. If the handler is None, an
1268 listed in the exc_tuple are caught. If the handler is None, an
1265 internal basic one is used, which just prints basic info.
1269 internal basic one is used, which just prints basic info.
1266
1270
1267 WARNING: by putting in your own exception handler into IPython's main
1271 WARNING: by putting in your own exception handler into IPython's main
1268 execution loop, you run a very good chance of nasty crashes. This
1272 execution loop, you run a very good chance of nasty crashes. This
1269 facility should only be used if you really know what you are doing."""
1273 facility should only be used if you really know what you are doing."""
1270
1274
1271 assert type(exc_tuple)==type(()) , \
1275 assert type(exc_tuple)==type(()) , \
1272 "The custom exceptions must be given AS A TUPLE."
1276 "The custom exceptions must be given AS A TUPLE."
1273
1277
1274 def dummy_handler(self,etype,value,tb):
1278 def dummy_handler(self,etype,value,tb):
1275 print '*** Simple custom exception handler ***'
1279 print '*** Simple custom exception handler ***'
1276 print 'Exception type :',etype
1280 print 'Exception type :',etype
1277 print 'Exception value:',value
1281 print 'Exception value:',value
1278 print 'Traceback :',tb
1282 print 'Traceback :',tb
1279 print 'Source code :','\n'.join(self.buffer)
1283 print 'Source code :','\n'.join(self.buffer)
1280
1284
1281 if handler is None: handler = dummy_handler
1285 if handler is None: handler = dummy_handler
1282
1286
1283 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1287 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1284 self.custom_exceptions = exc_tuple
1288 self.custom_exceptions = exc_tuple
1285
1289
1286 def excepthook(self, etype, value, tb):
1290 def excepthook(self, etype, value, tb):
1287 """One more defense for GUI apps that call sys.excepthook.
1291 """One more defense for GUI apps that call sys.excepthook.
1288
1292
1289 GUI frameworks like wxPython trap exceptions and call
1293 GUI frameworks like wxPython trap exceptions and call
1290 sys.excepthook themselves. I guess this is a feature that
1294 sys.excepthook themselves. I guess this is a feature that
1291 enables them to keep running after exceptions that would
1295 enables them to keep running after exceptions that would
1292 otherwise kill their mainloop. This is a bother for IPython
1296 otherwise kill their mainloop. This is a bother for IPython
1293 which excepts to catch all of the program exceptions with a try:
1297 which excepts to catch all of the program exceptions with a try:
1294 except: statement.
1298 except: statement.
1295
1299
1296 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1300 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1297 any app directly invokes sys.excepthook, it will look to the user like
1301 any app directly invokes sys.excepthook, it will look to the user like
1298 IPython crashed. In order to work around this, we can disable the
1302 IPython crashed. In order to work around this, we can disable the
1299 CrashHandler and replace it with this excepthook instead, which prints a
1303 CrashHandler and replace it with this excepthook instead, which prints a
1300 regular traceback using our InteractiveTB. In this fashion, apps which
1304 regular traceback using our InteractiveTB. In this fashion, apps which
1301 call sys.excepthook will generate a regular-looking exception from
1305 call sys.excepthook will generate a regular-looking exception from
1302 IPython, and the CrashHandler will only be triggered by real IPython
1306 IPython, and the CrashHandler will only be triggered by real IPython
1303 crashes.
1307 crashes.
1304
1308
1305 This hook should be used sparingly, only in places which are not likely
1309 This hook should be used sparingly, only in places which are not likely
1306 to be true IPython errors.
1310 to be true IPython errors.
1307 """
1311 """
1308 self.showtraceback((etype,value,tb),tb_offset=0)
1312 self.showtraceback((etype,value,tb),tb_offset=0)
1309
1313
1310 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1314 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1311 exception_only=False):
1315 exception_only=False):
1312 """Display the exception that just occurred.
1316 """Display the exception that just occurred.
1313
1317
1314 If nothing is known about the exception, this is the method which
1318 If nothing is known about the exception, this is the method which
1315 should be used throughout the code for presenting user tracebacks,
1319 should be used throughout the code for presenting user tracebacks,
1316 rather than directly invoking the InteractiveTB object.
1320 rather than directly invoking the InteractiveTB object.
1317
1321
1318 A specific showsyntaxerror() also exists, but this method can take
1322 A specific showsyntaxerror() also exists, but this method can take
1319 care of calling it if needed, so unless you are explicitly catching a
1323 care of calling it if needed, so unless you are explicitly catching a
1320 SyntaxError exception, don't try to analyze the stack manually and
1324 SyntaxError exception, don't try to analyze the stack manually and
1321 simply call this method."""
1325 simply call this method."""
1322
1326
1323 try:
1327 try:
1324 if exc_tuple is None:
1328 if exc_tuple is None:
1325 etype, value, tb = sys.exc_info()
1329 etype, value, tb = sys.exc_info()
1326 else:
1330 else:
1327 etype, value, tb = exc_tuple
1331 etype, value, tb = exc_tuple
1328
1332
1329 if etype is None:
1333 if etype is None:
1330 if hasattr(sys, 'last_type'):
1334 if hasattr(sys, 'last_type'):
1331 etype, value, tb = sys.last_type, sys.last_value, \
1335 etype, value, tb = sys.last_type, sys.last_value, \
1332 sys.last_traceback
1336 sys.last_traceback
1333 else:
1337 else:
1334 self.write('No traceback available to show.\n')
1338 self.write('No traceback available to show.\n')
1335 return
1339 return
1336
1340
1337 if etype is SyntaxError:
1341 if etype is SyntaxError:
1338 # Though this won't be called by syntax errors in the input
1342 # Though this won't be called by syntax errors in the input
1339 # line, there may be SyntaxError cases whith imported code.
1343 # line, there may be SyntaxError cases whith imported code.
1340 self.showsyntaxerror(filename)
1344 self.showsyntaxerror(filename)
1341 elif etype is UsageError:
1345 elif etype is UsageError:
1342 print "UsageError:", value
1346 print "UsageError:", value
1343 else:
1347 else:
1344 # WARNING: these variables are somewhat deprecated and not
1348 # WARNING: these variables are somewhat deprecated and not
1345 # necessarily safe to use in a threaded environment, but tools
1349 # necessarily safe to use in a threaded environment, but tools
1346 # like pdb depend on their existence, so let's set them. If we
1350 # like pdb depend on their existence, so let's set them. If we
1347 # find problems in the field, we'll need to revisit their use.
1351 # find problems in the field, we'll need to revisit their use.
1348 sys.last_type = etype
1352 sys.last_type = etype
1349 sys.last_value = value
1353 sys.last_value = value
1350 sys.last_traceback = tb
1354 sys.last_traceback = tb
1351
1355
1352 if etype in self.custom_exceptions:
1356 if etype in self.custom_exceptions:
1353 self.CustomTB(etype,value,tb)
1357 self.CustomTB(etype,value,tb)
1354 else:
1358 else:
1355 if exception_only:
1359 if exception_only:
1356 m = ('An exception has occurred, use %tb to see the '
1360 m = ('An exception has occurred, use %tb to see the '
1357 'full traceback.')
1361 'full traceback.')
1358 print m
1362 print m
1359 self.InteractiveTB.show_exception_only(etype, value)
1363 self.InteractiveTB.show_exception_only(etype, value)
1360 else:
1364 else:
1361 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1365 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1362 if self.InteractiveTB.call_pdb:
1366 if self.InteractiveTB.call_pdb:
1363 # pdb mucks up readline, fix it back
1367 # pdb mucks up readline, fix it back
1364 self.set_completer()
1368 self.set_completer()
1365
1369
1366 except KeyboardInterrupt:
1370 except KeyboardInterrupt:
1367 self.write("\nKeyboardInterrupt\n")
1371 self.write("\nKeyboardInterrupt\n")
1368
1372
1369
1373
1370 def showsyntaxerror(self, filename=None):
1374 def showsyntaxerror(self, filename=None):
1371 """Display the syntax error that just occurred.
1375 """Display the syntax error that just occurred.
1372
1376
1373 This doesn't display a stack trace because there isn't one.
1377 This doesn't display a stack trace because there isn't one.
1374
1378
1375 If a filename is given, it is stuffed in the exception instead
1379 If a filename is given, it is stuffed in the exception instead
1376 of what was there before (because Python's parser always uses
1380 of what was there before (because Python's parser always uses
1377 "<string>" when reading from a string).
1381 "<string>" when reading from a string).
1378 """
1382 """
1379 etype, value, last_traceback = sys.exc_info()
1383 etype, value, last_traceback = sys.exc_info()
1380
1384
1381 # See note about these variables in showtraceback() above
1385 # See note about these variables in showtraceback() above
1382 sys.last_type = etype
1386 sys.last_type = etype
1383 sys.last_value = value
1387 sys.last_value = value
1384 sys.last_traceback = last_traceback
1388 sys.last_traceback = last_traceback
1385
1389
1386 if filename and etype is SyntaxError:
1390 if filename and etype is SyntaxError:
1387 # Work hard to stuff the correct filename in the exception
1391 # Work hard to stuff the correct filename in the exception
1388 try:
1392 try:
1389 msg, (dummy_filename, lineno, offset, line) = value
1393 msg, (dummy_filename, lineno, offset, line) = value
1390 except:
1394 except:
1391 # Not the format we expect; leave it alone
1395 # Not the format we expect; leave it alone
1392 pass
1396 pass
1393 else:
1397 else:
1394 # Stuff in the right filename
1398 # Stuff in the right filename
1395 try:
1399 try:
1396 # Assume SyntaxError is a class exception
1400 # Assume SyntaxError is a class exception
1397 value = SyntaxError(msg, (filename, lineno, offset, line))
1401 value = SyntaxError(msg, (filename, lineno, offset, line))
1398 except:
1402 except:
1399 # If that failed, assume SyntaxError is a string
1403 # If that failed, assume SyntaxError is a string
1400 value = msg, (filename, lineno, offset, line)
1404 value = msg, (filename, lineno, offset, line)
1401 self.SyntaxTB(etype,value,[])
1405 self.SyntaxTB(etype,value,[])
1402
1406
1403 def edit_syntax_error(self):
1407 def edit_syntax_error(self):
1404 """The bottom half of the syntax error handler called in the main loop.
1408 """The bottom half of the syntax error handler called in the main loop.
1405
1409
1406 Loop until syntax error is fixed or user cancels.
1410 Loop until syntax error is fixed or user cancels.
1407 """
1411 """
1408
1412
1409 while self.SyntaxTB.last_syntax_error:
1413 while self.SyntaxTB.last_syntax_error:
1410 # copy and clear last_syntax_error
1414 # copy and clear last_syntax_error
1411 err = self.SyntaxTB.clear_err_state()
1415 err = self.SyntaxTB.clear_err_state()
1412 if not self._should_recompile(err):
1416 if not self._should_recompile(err):
1413 return
1417 return
1414 try:
1418 try:
1415 # may set last_syntax_error again if a SyntaxError is raised
1419 # may set last_syntax_error again if a SyntaxError is raised
1416 self.safe_execfile(err.filename,self.user_ns)
1420 self.safe_execfile(err.filename,self.user_ns)
1417 except:
1421 except:
1418 self.showtraceback()
1422 self.showtraceback()
1419 else:
1423 else:
1420 try:
1424 try:
1421 f = file(err.filename)
1425 f = file(err.filename)
1422 try:
1426 try:
1423 # This should be inside a display_trap block and I
1427 # This should be inside a display_trap block and I
1424 # think it is.
1428 # think it is.
1425 sys.displayhook(f.read())
1429 sys.displayhook(f.read())
1426 finally:
1430 finally:
1427 f.close()
1431 f.close()
1428 except:
1432 except:
1429 self.showtraceback()
1433 self.showtraceback()
1430
1434
1431 def _should_recompile(self,e):
1435 def _should_recompile(self,e):
1432 """Utility routine for edit_syntax_error"""
1436 """Utility routine for edit_syntax_error"""
1433
1437
1434 if e.filename in ('<ipython console>','<input>','<string>',
1438 if e.filename in ('<ipython console>','<input>','<string>',
1435 '<console>','<BackgroundJob compilation>',
1439 '<console>','<BackgroundJob compilation>',
1436 None):
1440 None):
1437
1441
1438 return False
1442 return False
1439 try:
1443 try:
1440 if (self.autoedit_syntax and
1444 if (self.autoedit_syntax and
1441 not self.ask_yes_no('Return to editor to correct syntax error? '
1445 not self.ask_yes_no('Return to editor to correct syntax error? '
1442 '[Y/n] ','y')):
1446 '[Y/n] ','y')):
1443 return False
1447 return False
1444 except EOFError:
1448 except EOFError:
1445 return False
1449 return False
1446
1450
1447 def int0(x):
1451 def int0(x):
1448 try:
1452 try:
1449 return int(x)
1453 return int(x)
1450 except TypeError:
1454 except TypeError:
1451 return 0
1455 return 0
1452 # always pass integer line and offset values to editor hook
1456 # always pass integer line and offset values to editor hook
1453 try:
1457 try:
1454 self.hooks.fix_error_editor(e.filename,
1458 self.hooks.fix_error_editor(e.filename,
1455 int0(e.lineno),int0(e.offset),e.msg)
1459 int0(e.lineno),int0(e.offset),e.msg)
1456 except TryNext:
1460 except TryNext:
1457 warn('Could not open editor')
1461 warn('Could not open editor')
1458 return False
1462 return False
1459 return True
1463 return True
1460
1464
1461 #-------------------------------------------------------------------------
1465 #-------------------------------------------------------------------------
1462 # Things related to tab completion
1466 # Things related to tab completion
1463 #-------------------------------------------------------------------------
1467 #-------------------------------------------------------------------------
1464
1468
1465 def complete(self, text):
1469 def complete(self, text):
1466 """Return a sorted list of all possible completions on text.
1470 """Return a sorted list of all possible completions on text.
1467
1471
1468 Inputs:
1472 Inputs:
1469
1473
1470 - text: a string of text to be completed on.
1474 - text: a string of text to be completed on.
1471
1475
1472 This is a wrapper around the completion mechanism, similar to what
1476 This is a wrapper around the completion mechanism, similar to what
1473 readline does at the command line when the TAB key is hit. By
1477 readline does at the command line when the TAB key is hit. By
1474 exposing it as a method, it can be used by other non-readline
1478 exposing it as a method, it can be used by other non-readline
1475 environments (such as GUIs) for text completion.
1479 environments (such as GUIs) for text completion.
1476
1480
1477 Simple usage example:
1481 Simple usage example:
1478
1482
1479 In [7]: x = 'hello'
1483 In [7]: x = 'hello'
1480
1484
1481 In [8]: x
1485 In [8]: x
1482 Out[8]: 'hello'
1486 Out[8]: 'hello'
1483
1487
1484 In [9]: print x
1488 In [9]: print x
1485 hello
1489 hello
1486
1490
1487 In [10]: _ip.complete('x.l')
1491 In [10]: _ip.complete('x.l')
1488 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1492 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1489 """
1493 """
1490
1494
1491 # Inject names into __builtin__ so we can complete on the added names.
1495 # Inject names into __builtin__ so we can complete on the added names.
1492 with self.builtin_trap:
1496 with self.builtin_trap:
1493 complete = self.Completer.complete
1497 complete = self.Completer.complete
1494 state = 0
1498 state = 0
1495 # use a dict so we get unique keys, since ipyhton's multiple
1499 # use a dict so we get unique keys, since ipyhton's multiple
1496 # completers can return duplicates. When we make 2.4 a requirement,
1500 # completers can return duplicates. When we make 2.4 a requirement,
1497 # start using sets instead, which are faster.
1501 # start using sets instead, which are faster.
1498 comps = {}
1502 comps = {}
1499 while True:
1503 while True:
1500 newcomp = complete(text,state,line_buffer=text)
1504 newcomp = complete(text,state,line_buffer=text)
1501 if newcomp is None:
1505 if newcomp is None:
1502 break
1506 break
1503 comps[newcomp] = 1
1507 comps[newcomp] = 1
1504 state += 1
1508 state += 1
1505 outcomps = comps.keys()
1509 outcomps = comps.keys()
1506 outcomps.sort()
1510 outcomps.sort()
1507 #print "T:",text,"OC:",outcomps # dbg
1511 #print "T:",text,"OC:",outcomps # dbg
1508 #print "vars:",self.user_ns.keys()
1512 #print "vars:",self.user_ns.keys()
1509 return outcomps
1513 return outcomps
1510
1514
1511 def set_custom_completer(self,completer,pos=0):
1515 def set_custom_completer(self,completer,pos=0):
1512 """Adds a new custom completer function.
1516 """Adds a new custom completer function.
1513
1517
1514 The position argument (defaults to 0) is the index in the completers
1518 The position argument (defaults to 0) is the index in the completers
1515 list where you want the completer to be inserted."""
1519 list where you want the completer to be inserted."""
1516
1520
1517 newcomp = new.instancemethod(completer,self.Completer,
1521 newcomp = new.instancemethod(completer,self.Completer,
1518 self.Completer.__class__)
1522 self.Completer.__class__)
1519 self.Completer.matchers.insert(pos,newcomp)
1523 self.Completer.matchers.insert(pos,newcomp)
1520
1524
1521 def set_completer(self):
1525 def set_completer(self):
1522 """Reset readline's completer to be our own."""
1526 """Reset readline's completer to be our own."""
1523 self.readline.set_completer(self.Completer.complete)
1527 self.readline.set_completer(self.Completer.complete)
1524
1528
1525 def set_completer_frame(self, frame=None):
1529 def set_completer_frame(self, frame=None):
1526 """Set the frame of the completer."""
1530 """Set the frame of the completer."""
1527 if frame:
1531 if frame:
1528 self.Completer.namespace = frame.f_locals
1532 self.Completer.namespace = frame.f_locals
1529 self.Completer.global_namespace = frame.f_globals
1533 self.Completer.global_namespace = frame.f_globals
1530 else:
1534 else:
1531 self.Completer.namespace = self.user_ns
1535 self.Completer.namespace = self.user_ns
1532 self.Completer.global_namespace = self.user_global_ns
1536 self.Completer.global_namespace = self.user_global_ns
1533
1537
1534 #-------------------------------------------------------------------------
1538 #-------------------------------------------------------------------------
1535 # Things related to readline
1539 # Things related to readline
1536 #-------------------------------------------------------------------------
1540 #-------------------------------------------------------------------------
1537
1541
1538 def init_readline(self):
1542 def init_readline(self):
1539 """Command history completion/saving/reloading."""
1543 """Command history completion/saving/reloading."""
1540
1544
1541 if self.readline_use:
1545 if self.readline_use:
1542 import IPython.utils.rlineimpl as readline
1546 import IPython.utils.rlineimpl as readline
1543
1547
1544 self.rl_next_input = None
1548 self.rl_next_input = None
1545 self.rl_do_indent = False
1549 self.rl_do_indent = False
1546
1550
1547 if not self.readline_use or not readline.have_readline:
1551 if not self.readline_use or not readline.have_readline:
1548 self.has_readline = False
1552 self.has_readline = False
1549 self.readline = None
1553 self.readline = None
1550 # Set a number of methods that depend on readline to be no-op
1554 # Set a number of methods that depend on readline to be no-op
1551 self.savehist = no_op
1555 self.savehist = no_op
1552 self.reloadhist = no_op
1556 self.reloadhist = no_op
1553 self.set_completer = no_op
1557 self.set_completer = no_op
1554 self.set_custom_completer = no_op
1558 self.set_custom_completer = no_op
1555 self.set_completer_frame = no_op
1559 self.set_completer_frame = no_op
1556 warn('Readline services not available or not loaded.')
1560 warn('Readline services not available or not loaded.')
1557 else:
1561 else:
1558 self.has_readline = True
1562 self.has_readline = True
1559 self.readline = readline
1563 self.readline = readline
1560 sys.modules['readline'] = readline
1564 sys.modules['readline'] = readline
1561 import atexit
1565 import atexit
1562 from IPython.core.completer import IPCompleter
1566 from IPython.core.completer import IPCompleter
1563 self.Completer = IPCompleter(self,
1567 self.Completer = IPCompleter(self,
1564 self.user_ns,
1568 self.user_ns,
1565 self.user_global_ns,
1569 self.user_global_ns,
1566 self.readline_omit__names,
1570 self.readline_omit__names,
1567 self.alias_manager.alias_table)
1571 self.alias_manager.alias_table)
1568 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1572 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1569 self.strdispatchers['complete_command'] = sdisp
1573 self.strdispatchers['complete_command'] = sdisp
1570 self.Completer.custom_completers = sdisp
1574 self.Completer.custom_completers = sdisp
1571 # Platform-specific configuration
1575 # Platform-specific configuration
1572 if os.name == 'nt':
1576 if os.name == 'nt':
1573 self.readline_startup_hook = readline.set_pre_input_hook
1577 self.readline_startup_hook = readline.set_pre_input_hook
1574 else:
1578 else:
1575 self.readline_startup_hook = readline.set_startup_hook
1579 self.readline_startup_hook = readline.set_startup_hook
1576
1580
1577 # Load user's initrc file (readline config)
1581 # Load user's initrc file (readline config)
1578 # Or if libedit is used, load editrc.
1582 # Or if libedit is used, load editrc.
1579 inputrc_name = os.environ.get('INPUTRC')
1583 inputrc_name = os.environ.get('INPUTRC')
1580 if inputrc_name is None:
1584 if inputrc_name is None:
1581 home_dir = get_home_dir()
1585 home_dir = get_home_dir()
1582 if home_dir is not None:
1586 if home_dir is not None:
1583 inputrc_name = '.inputrc'
1587 inputrc_name = '.inputrc'
1584 if readline.uses_libedit:
1588 if readline.uses_libedit:
1585 inputrc_name = '.editrc'
1589 inputrc_name = '.editrc'
1586 inputrc_name = os.path.join(home_dir, inputrc_name)
1590 inputrc_name = os.path.join(home_dir, inputrc_name)
1587 if os.path.isfile(inputrc_name):
1591 if os.path.isfile(inputrc_name):
1588 try:
1592 try:
1589 readline.read_init_file(inputrc_name)
1593 readline.read_init_file(inputrc_name)
1590 except:
1594 except:
1591 warn('Problems reading readline initialization file <%s>'
1595 warn('Problems reading readline initialization file <%s>'
1592 % inputrc_name)
1596 % inputrc_name)
1593
1597
1594 # save this in sys so embedded copies can restore it properly
1598 # save this in sys so embedded copies can restore it properly
1595 sys.ipcompleter = self.Completer.complete
1599 sys.ipcompleter = self.Completer.complete
1596 self.set_completer()
1600 self.set_completer()
1597
1601
1598 # Configure readline according to user's prefs
1602 # Configure readline according to user's prefs
1599 # This is only done if GNU readline is being used. If libedit
1603 # This is only done if GNU readline is being used. If libedit
1600 # is being used (as on Leopard) the readline config is
1604 # is being used (as on Leopard) the readline config is
1601 # not run as the syntax for libedit is different.
1605 # not run as the syntax for libedit is different.
1602 if not readline.uses_libedit:
1606 if not readline.uses_libedit:
1603 for rlcommand in self.readline_parse_and_bind:
1607 for rlcommand in self.readline_parse_and_bind:
1604 #print "loading rl:",rlcommand # dbg
1608 #print "loading rl:",rlcommand # dbg
1605 readline.parse_and_bind(rlcommand)
1609 readline.parse_and_bind(rlcommand)
1606
1610
1607 # Remove some chars from the delimiters list. If we encounter
1611 # Remove some chars from the delimiters list. If we encounter
1608 # unicode chars, discard them.
1612 # unicode chars, discard them.
1609 delims = readline.get_completer_delims().encode("ascii", "ignore")
1613 delims = readline.get_completer_delims().encode("ascii", "ignore")
1610 delims = delims.translate(string._idmap,
1614 delims = delims.translate(string._idmap,
1611 self.readline_remove_delims)
1615 self.readline_remove_delims)
1612 readline.set_completer_delims(delims)
1616 readline.set_completer_delims(delims)
1613 # otherwise we end up with a monster history after a while:
1617 # otherwise we end up with a monster history after a while:
1614 readline.set_history_length(1000)
1618 readline.set_history_length(1000)
1615 try:
1619 try:
1616 #print '*** Reading readline history' # dbg
1620 #print '*** Reading readline history' # dbg
1617 readline.read_history_file(self.histfile)
1621 readline.read_history_file(self.histfile)
1618 except IOError:
1622 except IOError:
1619 pass # It doesn't exist yet.
1623 pass # It doesn't exist yet.
1620
1624
1621 atexit.register(self.atexit_operations)
1625 atexit.register(self.atexit_operations)
1622 del atexit
1626 del atexit
1623
1627
1624 # Configure auto-indent for all platforms
1628 # Configure auto-indent for all platforms
1625 self.set_autoindent(self.autoindent)
1629 self.set_autoindent(self.autoindent)
1626
1630
1627 def set_next_input(self, s):
1631 def set_next_input(self, s):
1628 """ Sets the 'default' input string for the next command line.
1632 """ Sets the 'default' input string for the next command line.
1629
1633
1630 Requires readline.
1634 Requires readline.
1631
1635
1632 Example:
1636 Example:
1633
1637
1634 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1638 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1635 [D:\ipython]|2> Hello Word_ # cursor is here
1639 [D:\ipython]|2> Hello Word_ # cursor is here
1636 """
1640 """
1637
1641
1638 self.rl_next_input = s
1642 self.rl_next_input = s
1639
1643
1640 def pre_readline(self):
1644 def pre_readline(self):
1641 """readline hook to be used at the start of each line.
1645 """readline hook to be used at the start of each line.
1642
1646
1643 Currently it handles auto-indent only."""
1647 Currently it handles auto-indent only."""
1644
1648
1645 #debugx('self.indent_current_nsp','pre_readline:')
1649 #debugx('self.indent_current_nsp','pre_readline:')
1646
1650
1647 if self.rl_do_indent:
1651 if self.rl_do_indent:
1648 self.readline.insert_text(self._indent_current_str())
1652 self.readline.insert_text(self._indent_current_str())
1649 if self.rl_next_input is not None:
1653 if self.rl_next_input is not None:
1650 self.readline.insert_text(self.rl_next_input)
1654 self.readline.insert_text(self.rl_next_input)
1651 self.rl_next_input = None
1655 self.rl_next_input = None
1652
1656
1653 def _indent_current_str(self):
1657 def _indent_current_str(self):
1654 """return the current level of indentation as a string"""
1658 """return the current level of indentation as a string"""
1655 return self.indent_current_nsp * ' '
1659 return self.indent_current_nsp * ' '
1656
1660
1657 #-------------------------------------------------------------------------
1661 #-------------------------------------------------------------------------
1658 # Things related to magics
1662 # Things related to magics
1659 #-------------------------------------------------------------------------
1663 #-------------------------------------------------------------------------
1660
1664
1661 def init_magics(self):
1665 def init_magics(self):
1662 # Set user colors (don't do it in the constructor above so that it
1666 # Set user colors (don't do it in the constructor above so that it
1663 # doesn't crash if colors option is invalid)
1667 # doesn't crash if colors option is invalid)
1664 self.magic_colors(self.colors)
1668 self.magic_colors(self.colors)
1665 # History was moved to a separate module
1669 # History was moved to a separate module
1666 from . import history
1670 from . import history
1667 history.init_ipython(self)
1671 history.init_ipython(self)
1668
1672
1669 def magic(self,arg_s):
1673 def magic(self,arg_s):
1670 """Call a magic function by name.
1674 """Call a magic function by name.
1671
1675
1672 Input: a string containing the name of the magic function to call and any
1676 Input: a string containing the name of the magic function to call and any
1673 additional arguments to be passed to the magic.
1677 additional arguments to be passed to the magic.
1674
1678
1675 magic('name -opt foo bar') is equivalent to typing at the ipython
1679 magic('name -opt foo bar') is equivalent to typing at the ipython
1676 prompt:
1680 prompt:
1677
1681
1678 In[1]: %name -opt foo bar
1682 In[1]: %name -opt foo bar
1679
1683
1680 To call a magic without arguments, simply use magic('name').
1684 To call a magic without arguments, simply use magic('name').
1681
1685
1682 This provides a proper Python function to call IPython's magics in any
1686 This provides a proper Python function to call IPython's magics in any
1683 valid Python code you can type at the interpreter, including loops and
1687 valid Python code you can type at the interpreter, including loops and
1684 compound statements.
1688 compound statements.
1685 """
1689 """
1686 args = arg_s.split(' ',1)
1690 args = arg_s.split(' ',1)
1687 magic_name = args[0]
1691 magic_name = args[0]
1688 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1692 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1689
1693
1690 try:
1694 try:
1691 magic_args = args[1]
1695 magic_args = args[1]
1692 except IndexError:
1696 except IndexError:
1693 magic_args = ''
1697 magic_args = ''
1694 fn = getattr(self,'magic_'+magic_name,None)
1698 fn = getattr(self,'magic_'+magic_name,None)
1695 if fn is None:
1699 if fn is None:
1696 error("Magic function `%s` not found." % magic_name)
1700 error("Magic function `%s` not found." % magic_name)
1697 else:
1701 else:
1698 magic_args = self.var_expand(magic_args,1)
1702 magic_args = self.var_expand(magic_args,1)
1699 with nested(self.builtin_trap,):
1703 with nested(self.builtin_trap,):
1700 result = fn(magic_args)
1704 result = fn(magic_args)
1701 return result
1705 return result
1702
1706
1703 def define_magic(self, magicname, func):
1707 def define_magic(self, magicname, func):
1704 """Expose own function as magic function for ipython
1708 """Expose own function as magic function for ipython
1705
1709
1706 def foo_impl(self,parameter_s=''):
1710 def foo_impl(self,parameter_s=''):
1707 'My very own magic!. (Use docstrings, IPython reads them).'
1711 'My very own magic!. (Use docstrings, IPython reads them).'
1708 print 'Magic function. Passed parameter is between < >:'
1712 print 'Magic function. Passed parameter is between < >:'
1709 print '<%s>' % parameter_s
1713 print '<%s>' % parameter_s
1710 print 'The self object is:',self
1714 print 'The self object is:',self
1711
1715
1712 self.define_magic('foo',foo_impl)
1716 self.define_magic('foo',foo_impl)
1713 """
1717 """
1714
1718
1715 import new
1719 import new
1716 im = new.instancemethod(func,self, self.__class__)
1720 im = new.instancemethod(func,self, self.__class__)
1717 old = getattr(self, "magic_" + magicname, None)
1721 old = getattr(self, "magic_" + magicname, None)
1718 setattr(self, "magic_" + magicname, im)
1722 setattr(self, "magic_" + magicname, im)
1719 return old
1723 return old
1720
1724
1721 #-------------------------------------------------------------------------
1725 #-------------------------------------------------------------------------
1722 # Things related to macros
1726 # Things related to macros
1723 #-------------------------------------------------------------------------
1727 #-------------------------------------------------------------------------
1724
1728
1725 def define_macro(self, name, themacro):
1729 def define_macro(self, name, themacro):
1726 """Define a new macro
1730 """Define a new macro
1727
1731
1728 Parameters
1732 Parameters
1729 ----------
1733 ----------
1730 name : str
1734 name : str
1731 The name of the macro.
1735 The name of the macro.
1732 themacro : str or Macro
1736 themacro : str or Macro
1733 The action to do upon invoking the macro. If a string, a new
1737 The action to do upon invoking the macro. If a string, a new
1734 Macro object is created by passing the string to it.
1738 Macro object is created by passing the string to it.
1735 """
1739 """
1736
1740
1737 from IPython.core import macro
1741 from IPython.core import macro
1738
1742
1739 if isinstance(themacro, basestring):
1743 if isinstance(themacro, basestring):
1740 themacro = macro.Macro(themacro)
1744 themacro = macro.Macro(themacro)
1741 if not isinstance(themacro, macro.Macro):
1745 if not isinstance(themacro, macro.Macro):
1742 raise ValueError('A macro must be a string or a Macro instance.')
1746 raise ValueError('A macro must be a string or a Macro instance.')
1743 self.user_ns[name] = themacro
1747 self.user_ns[name] = themacro
1744
1748
1745 #-------------------------------------------------------------------------
1749 #-------------------------------------------------------------------------
1746 # Things related to the running of system commands
1750 # Things related to the running of system commands
1747 #-------------------------------------------------------------------------
1751 #-------------------------------------------------------------------------
1748
1752
1749 def system(self, cmd):
1753 def system(self, cmd):
1750 """Make a system call, using IPython."""
1754 """Make a system call, using IPython."""
1751 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1755 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1752
1756
1753 #-------------------------------------------------------------------------
1757 #-------------------------------------------------------------------------
1754 # Things related to aliases
1758 # Things related to aliases
1755 #-------------------------------------------------------------------------
1759 #-------------------------------------------------------------------------
1756
1760
1757 def init_alias(self):
1761 def init_alias(self):
1758 self.alias_manager = AliasManager(self, config=self.config)
1762 self.alias_manager = AliasManager(self, config=self.config)
1759 self.ns_table['alias'] = self.alias_manager.alias_table,
1763 self.ns_table['alias'] = self.alias_manager.alias_table,
1760
1764
1761 #-------------------------------------------------------------------------
1765 #-------------------------------------------------------------------------
1762 # Things related to extensions
1766 # Things related to extensions and plugins
1763 #-------------------------------------------------------------------------
1767 #-------------------------------------------------------------------------
1764
1768
1765 def init_extension_manager(self):
1769 def init_extension_manager(self):
1766 self.extension_manager = ExtensionManager(self, config=self.config)
1770 self.extension_manager = ExtensionManager(self, config=self.config)
1767
1771
1772 def init_plugin_manager(self):
1773 self.plugin_manager = PluginManager(config=self.config)
1774
1768 #-------------------------------------------------------------------------
1775 #-------------------------------------------------------------------------
1769 # Things related to the running of code
1776 # Things related to the running of code
1770 #-------------------------------------------------------------------------
1777 #-------------------------------------------------------------------------
1771
1778
1772 def ex(self, cmd):
1779 def ex(self, cmd):
1773 """Execute a normal python statement in user namespace."""
1780 """Execute a normal python statement in user namespace."""
1774 with nested(self.builtin_trap,):
1781 with nested(self.builtin_trap,):
1775 exec cmd in self.user_global_ns, self.user_ns
1782 exec cmd in self.user_global_ns, self.user_ns
1776
1783
1777 def ev(self, expr):
1784 def ev(self, expr):
1778 """Evaluate python expression expr in user namespace.
1785 """Evaluate python expression expr in user namespace.
1779
1786
1780 Returns the result of evaluation
1787 Returns the result of evaluation
1781 """
1788 """
1782 with nested(self.builtin_trap,):
1789 with nested(self.builtin_trap,):
1783 return eval(expr, self.user_global_ns, self.user_ns)
1790 return eval(expr, self.user_global_ns, self.user_ns)
1784
1791
1785 def mainloop(self, display_banner=None):
1792 def mainloop(self, display_banner=None):
1786 """Start the mainloop.
1793 """Start the mainloop.
1787
1794
1788 If an optional banner argument is given, it will override the
1795 If an optional banner argument is given, it will override the
1789 internally created default banner.
1796 internally created default banner.
1790 """
1797 """
1791
1798
1792 with nested(self.builtin_trap, self.display_trap):
1799 with nested(self.builtin_trap, self.display_trap):
1793
1800
1794 # if you run stuff with -c <cmd>, raw hist is not updated
1801 # if you run stuff with -c <cmd>, raw hist is not updated
1795 # ensure that it's in sync
1802 # ensure that it's in sync
1796 if len(self.input_hist) != len (self.input_hist_raw):
1803 if len(self.input_hist) != len (self.input_hist_raw):
1797 self.input_hist_raw = InputList(self.input_hist)
1804 self.input_hist_raw = InputList(self.input_hist)
1798
1805
1799 while 1:
1806 while 1:
1800 try:
1807 try:
1801 self.interact(display_banner=display_banner)
1808 self.interact(display_banner=display_banner)
1802 #self.interact_with_readline()
1809 #self.interact_with_readline()
1803 # XXX for testing of a readline-decoupled repl loop, call
1810 # XXX for testing of a readline-decoupled repl loop, call
1804 # interact_with_readline above
1811 # interact_with_readline above
1805 break
1812 break
1806 except KeyboardInterrupt:
1813 except KeyboardInterrupt:
1807 # this should not be necessary, but KeyboardInterrupt
1814 # this should not be necessary, but KeyboardInterrupt
1808 # handling seems rather unpredictable...
1815 # handling seems rather unpredictable...
1809 self.write("\nKeyboardInterrupt in interact()\n")
1816 self.write("\nKeyboardInterrupt in interact()\n")
1810
1817
1811 def interact_prompt(self):
1818 def interact_prompt(self):
1812 """ Print the prompt (in read-eval-print loop)
1819 """ Print the prompt (in read-eval-print loop)
1813
1820
1814 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1821 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1815 used in standard IPython flow.
1822 used in standard IPython flow.
1816 """
1823 """
1817 if self.more:
1824 if self.more:
1818 try:
1825 try:
1819 prompt = self.hooks.generate_prompt(True)
1826 prompt = self.hooks.generate_prompt(True)
1820 except:
1827 except:
1821 self.showtraceback()
1828 self.showtraceback()
1822 if self.autoindent:
1829 if self.autoindent:
1823 self.rl_do_indent = True
1830 self.rl_do_indent = True
1824
1831
1825 else:
1832 else:
1826 try:
1833 try:
1827 prompt = self.hooks.generate_prompt(False)
1834 prompt = self.hooks.generate_prompt(False)
1828 except:
1835 except:
1829 self.showtraceback()
1836 self.showtraceback()
1830 self.write(prompt)
1837 self.write(prompt)
1831
1838
1832 def interact_handle_input(self,line):
1839 def interact_handle_input(self,line):
1833 """ Handle the input line (in read-eval-print loop)
1840 """ Handle the input line (in read-eval-print loop)
1834
1841
1835 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1842 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1836 used in standard IPython flow.
1843 used in standard IPython flow.
1837 """
1844 """
1838 if line.lstrip() == line:
1845 if line.lstrip() == line:
1839 self.shadowhist.add(line.strip())
1846 self.shadowhist.add(line.strip())
1840 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1847 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1841
1848
1842 if line.strip():
1849 if line.strip():
1843 if self.more:
1850 if self.more:
1844 self.input_hist_raw[-1] += '%s\n' % line
1851 self.input_hist_raw[-1] += '%s\n' % line
1845 else:
1852 else:
1846 self.input_hist_raw.append('%s\n' % line)
1853 self.input_hist_raw.append('%s\n' % line)
1847
1854
1848
1855
1849 self.more = self.push_line(lineout)
1856 self.more = self.push_line(lineout)
1850 if (self.SyntaxTB.last_syntax_error and
1857 if (self.SyntaxTB.last_syntax_error and
1851 self.autoedit_syntax):
1858 self.autoedit_syntax):
1852 self.edit_syntax_error()
1859 self.edit_syntax_error()
1853
1860
1854 def interact_with_readline(self):
1861 def interact_with_readline(self):
1855 """ Demo of using interact_handle_input, interact_prompt
1862 """ Demo of using interact_handle_input, interact_prompt
1856
1863
1857 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1864 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1858 it should work like this.
1865 it should work like this.
1859 """
1866 """
1860 self.readline_startup_hook(self.pre_readline)
1867 self.readline_startup_hook(self.pre_readline)
1861 while not self.exit_now:
1868 while not self.exit_now:
1862 self.interact_prompt()
1869 self.interact_prompt()
1863 if self.more:
1870 if self.more:
1864 self.rl_do_indent = True
1871 self.rl_do_indent = True
1865 else:
1872 else:
1866 self.rl_do_indent = False
1873 self.rl_do_indent = False
1867 line = raw_input_original().decode(self.stdin_encoding)
1874 line = raw_input_original().decode(self.stdin_encoding)
1868 self.interact_handle_input(line)
1875 self.interact_handle_input(line)
1869
1876
1870 def interact(self, display_banner=None):
1877 def interact(self, display_banner=None):
1871 """Closely emulate the interactive Python console."""
1878 """Closely emulate the interactive Python console."""
1872
1879
1873 # batch run -> do not interact
1880 # batch run -> do not interact
1874 if self.exit_now:
1881 if self.exit_now:
1875 return
1882 return
1876
1883
1877 if display_banner is None:
1884 if display_banner is None:
1878 display_banner = self.display_banner
1885 display_banner = self.display_banner
1879 if display_banner:
1886 if display_banner:
1880 self.show_banner()
1887 self.show_banner()
1881
1888
1882 more = 0
1889 more = 0
1883
1890
1884 # Mark activity in the builtins
1891 # Mark activity in the builtins
1885 __builtin__.__dict__['__IPYTHON__active'] += 1
1892 __builtin__.__dict__['__IPYTHON__active'] += 1
1886
1893
1887 if self.has_readline:
1894 if self.has_readline:
1888 self.readline_startup_hook(self.pre_readline)
1895 self.readline_startup_hook(self.pre_readline)
1889 # exit_now is set by a call to %Exit or %Quit, through the
1896 # exit_now is set by a call to %Exit or %Quit, through the
1890 # ask_exit callback.
1897 # ask_exit callback.
1891
1898
1892 while not self.exit_now:
1899 while not self.exit_now:
1893 self.hooks.pre_prompt_hook()
1900 self.hooks.pre_prompt_hook()
1894 if more:
1901 if more:
1895 try:
1902 try:
1896 prompt = self.hooks.generate_prompt(True)
1903 prompt = self.hooks.generate_prompt(True)
1897 except:
1904 except:
1898 self.showtraceback()
1905 self.showtraceback()
1899 if self.autoindent:
1906 if self.autoindent:
1900 self.rl_do_indent = True
1907 self.rl_do_indent = True
1901
1908
1902 else:
1909 else:
1903 try:
1910 try:
1904 prompt = self.hooks.generate_prompt(False)
1911 prompt = self.hooks.generate_prompt(False)
1905 except:
1912 except:
1906 self.showtraceback()
1913 self.showtraceback()
1907 try:
1914 try:
1908 line = self.raw_input(prompt, more)
1915 line = self.raw_input(prompt, more)
1909 if self.exit_now:
1916 if self.exit_now:
1910 # quick exit on sys.std[in|out] close
1917 # quick exit on sys.std[in|out] close
1911 break
1918 break
1912 if self.autoindent:
1919 if self.autoindent:
1913 self.rl_do_indent = False
1920 self.rl_do_indent = False
1914
1921
1915 except KeyboardInterrupt:
1922 except KeyboardInterrupt:
1916 #double-guard against keyboardinterrupts during kbdint handling
1923 #double-guard against keyboardinterrupts during kbdint handling
1917 try:
1924 try:
1918 self.write('\nKeyboardInterrupt\n')
1925 self.write('\nKeyboardInterrupt\n')
1919 self.resetbuffer()
1926 self.resetbuffer()
1920 # keep cache in sync with the prompt counter:
1927 # keep cache in sync with the prompt counter:
1921 self.outputcache.prompt_count -= 1
1928 self.outputcache.prompt_count -= 1
1922
1929
1923 if self.autoindent:
1930 if self.autoindent:
1924 self.indent_current_nsp = 0
1931 self.indent_current_nsp = 0
1925 more = 0
1932 more = 0
1926 except KeyboardInterrupt:
1933 except KeyboardInterrupt:
1927 pass
1934 pass
1928 except EOFError:
1935 except EOFError:
1929 if self.autoindent:
1936 if self.autoindent:
1930 self.rl_do_indent = False
1937 self.rl_do_indent = False
1931 if self.has_readline:
1938 if self.has_readline:
1932 self.readline_startup_hook(None)
1939 self.readline_startup_hook(None)
1933 self.write('\n')
1940 self.write('\n')
1934 self.exit()
1941 self.exit()
1935 except bdb.BdbQuit:
1942 except bdb.BdbQuit:
1936 warn('The Python debugger has exited with a BdbQuit exception.\n'
1943 warn('The Python debugger has exited with a BdbQuit exception.\n'
1937 'Because of how pdb handles the stack, it is impossible\n'
1944 'Because of how pdb handles the stack, it is impossible\n'
1938 'for IPython to properly format this particular exception.\n'
1945 'for IPython to properly format this particular exception.\n'
1939 'IPython will resume normal operation.')
1946 'IPython will resume normal operation.')
1940 except:
1947 except:
1941 # exceptions here are VERY RARE, but they can be triggered
1948 # exceptions here are VERY RARE, but they can be triggered
1942 # asynchronously by signal handlers, for example.
1949 # asynchronously by signal handlers, for example.
1943 self.showtraceback()
1950 self.showtraceback()
1944 else:
1951 else:
1945 more = self.push_line(line)
1952 more = self.push_line(line)
1946 if (self.SyntaxTB.last_syntax_error and
1953 if (self.SyntaxTB.last_syntax_error and
1947 self.autoedit_syntax):
1954 self.autoedit_syntax):
1948 self.edit_syntax_error()
1955 self.edit_syntax_error()
1949
1956
1950 # We are off again...
1957 # We are off again...
1951 __builtin__.__dict__['__IPYTHON__active'] -= 1
1958 __builtin__.__dict__['__IPYTHON__active'] -= 1
1952
1959
1953 # Turn off the exit flag, so the mainloop can be restarted if desired
1960 # Turn off the exit flag, so the mainloop can be restarted if desired
1954 self.exit_now = False
1961 self.exit_now = False
1955
1962
1956 def safe_execfile(self, fname, *where, **kw):
1963 def safe_execfile(self, fname, *where, **kw):
1957 """A safe version of the builtin execfile().
1964 """A safe version of the builtin execfile().
1958
1965
1959 This version will never throw an exception, but instead print
1966 This version will never throw an exception, but instead print
1960 helpful error messages to the screen. This only works on pure
1967 helpful error messages to the screen. This only works on pure
1961 Python files with the .py extension.
1968 Python files with the .py extension.
1962
1969
1963 Parameters
1970 Parameters
1964 ----------
1971 ----------
1965 fname : string
1972 fname : string
1966 The name of the file to be executed.
1973 The name of the file to be executed.
1967 where : tuple
1974 where : tuple
1968 One or two namespaces, passed to execfile() as (globals,locals).
1975 One or two namespaces, passed to execfile() as (globals,locals).
1969 If only one is given, it is passed as both.
1976 If only one is given, it is passed as both.
1970 exit_ignore : bool (False)
1977 exit_ignore : bool (False)
1971 If True, then silence SystemExit for non-zero status (it is always
1978 If True, then silence SystemExit for non-zero status (it is always
1972 silenced for zero status, as it is so common).
1979 silenced for zero status, as it is so common).
1973 """
1980 """
1974 kw.setdefault('exit_ignore', False)
1981 kw.setdefault('exit_ignore', False)
1975
1982
1976 fname = os.path.abspath(os.path.expanduser(fname))
1983 fname = os.path.abspath(os.path.expanduser(fname))
1977
1984
1978 # Make sure we have a .py file
1985 # Make sure we have a .py file
1979 if not fname.endswith('.py'):
1986 if not fname.endswith('.py'):
1980 warn('File must end with .py to be run using execfile: <%s>' % fname)
1987 warn('File must end with .py to be run using execfile: <%s>' % fname)
1981
1988
1982 # Make sure we can open the file
1989 # Make sure we can open the file
1983 try:
1990 try:
1984 with open(fname) as thefile:
1991 with open(fname) as thefile:
1985 pass
1992 pass
1986 except:
1993 except:
1987 warn('Could not open file <%s> for safe execution.' % fname)
1994 warn('Could not open file <%s> for safe execution.' % fname)
1988 return
1995 return
1989
1996
1990 # Find things also in current directory. This is needed to mimic the
1997 # Find things also in current directory. This is needed to mimic the
1991 # behavior of running a script from the system command line, where
1998 # behavior of running a script from the system command line, where
1992 # Python inserts the script's directory into sys.path
1999 # Python inserts the script's directory into sys.path
1993 dname = os.path.dirname(fname)
2000 dname = os.path.dirname(fname)
1994
2001
1995 with prepended_to_syspath(dname):
2002 with prepended_to_syspath(dname):
1996 try:
2003 try:
1997 execfile(fname,*where)
2004 execfile(fname,*where)
1998 except SystemExit, status:
2005 except SystemExit, status:
1999 # If the call was made with 0 or None exit status (sys.exit(0)
2006 # If the call was made with 0 or None exit status (sys.exit(0)
2000 # or sys.exit() ), don't bother showing a traceback, as both of
2007 # or sys.exit() ), don't bother showing a traceback, as both of
2001 # these are considered normal by the OS:
2008 # these are considered normal by the OS:
2002 # > python -c'import sys;sys.exit(0)'; echo $?
2009 # > python -c'import sys;sys.exit(0)'; echo $?
2003 # 0
2010 # 0
2004 # > python -c'import sys;sys.exit()'; echo $?
2011 # > python -c'import sys;sys.exit()'; echo $?
2005 # 0
2012 # 0
2006 # For other exit status, we show the exception unless
2013 # For other exit status, we show the exception unless
2007 # explicitly silenced, but only in short form.
2014 # explicitly silenced, but only in short form.
2008 if status.code not in (0, None) and not kw['exit_ignore']:
2015 if status.code not in (0, None) and not kw['exit_ignore']:
2009 self.showtraceback(exception_only=True)
2016 self.showtraceback(exception_only=True)
2010 except:
2017 except:
2011 self.showtraceback()
2018 self.showtraceback()
2012
2019
2013 def safe_execfile_ipy(self, fname):
2020 def safe_execfile_ipy(self, fname):
2014 """Like safe_execfile, but for .ipy files with IPython syntax.
2021 """Like safe_execfile, but for .ipy files with IPython syntax.
2015
2022
2016 Parameters
2023 Parameters
2017 ----------
2024 ----------
2018 fname : str
2025 fname : str
2019 The name of the file to execute. The filename must have a
2026 The name of the file to execute. The filename must have a
2020 .ipy extension.
2027 .ipy extension.
2021 """
2028 """
2022 fname = os.path.abspath(os.path.expanduser(fname))
2029 fname = os.path.abspath(os.path.expanduser(fname))
2023
2030
2024 # Make sure we have a .py file
2031 # Make sure we have a .py file
2025 if not fname.endswith('.ipy'):
2032 if not fname.endswith('.ipy'):
2026 warn('File must end with .py to be run using execfile: <%s>' % fname)
2033 warn('File must end with .py to be run using execfile: <%s>' % fname)
2027
2034
2028 # Make sure we can open the file
2035 # Make sure we can open the file
2029 try:
2036 try:
2030 with open(fname) as thefile:
2037 with open(fname) as thefile:
2031 pass
2038 pass
2032 except:
2039 except:
2033 warn('Could not open file <%s> for safe execution.' % fname)
2040 warn('Could not open file <%s> for safe execution.' % fname)
2034 return
2041 return
2035
2042
2036 # Find things also in current directory. This is needed to mimic the
2043 # Find things also in current directory. This is needed to mimic the
2037 # behavior of running a script from the system command line, where
2044 # behavior of running a script from the system command line, where
2038 # Python inserts the script's directory into sys.path
2045 # Python inserts the script's directory into sys.path
2039 dname = os.path.dirname(fname)
2046 dname = os.path.dirname(fname)
2040
2047
2041 with prepended_to_syspath(dname):
2048 with prepended_to_syspath(dname):
2042 try:
2049 try:
2043 with open(fname) as thefile:
2050 with open(fname) as thefile:
2044 script = thefile.read()
2051 script = thefile.read()
2045 # self.runlines currently captures all exceptions
2052 # self.runlines currently captures all exceptions
2046 # raise in user code. It would be nice if there were
2053 # raise in user code. It would be nice if there were
2047 # versions of runlines, execfile that did raise, so
2054 # versions of runlines, execfile that did raise, so
2048 # we could catch the errors.
2055 # we could catch the errors.
2049 self.runlines(script, clean=True)
2056 self.runlines(script, clean=True)
2050 except:
2057 except:
2051 self.showtraceback()
2058 self.showtraceback()
2052 warn('Unknown failure executing file: <%s>' % fname)
2059 warn('Unknown failure executing file: <%s>' % fname)
2053
2060
2054 def _is_secondary_block_start(self, s):
2061 def _is_secondary_block_start(self, s):
2055 if not s.endswith(':'):
2062 if not s.endswith(':'):
2056 return False
2063 return False
2057 if (s.startswith('elif') or
2064 if (s.startswith('elif') or
2058 s.startswith('else') or
2065 s.startswith('else') or
2059 s.startswith('except') or
2066 s.startswith('except') or
2060 s.startswith('finally')):
2067 s.startswith('finally')):
2061 return True
2068 return True
2062
2069
2063 def cleanup_ipy_script(self, script):
2070 def cleanup_ipy_script(self, script):
2064 """Make a script safe for self.runlines()
2071 """Make a script safe for self.runlines()
2065
2072
2066 Currently, IPython is lines based, with blocks being detected by
2073 Currently, IPython is lines based, with blocks being detected by
2067 empty lines. This is a problem for block based scripts that may
2074 empty lines. This is a problem for block based scripts that may
2068 not have empty lines after blocks. This script adds those empty
2075 not have empty lines after blocks. This script adds those empty
2069 lines to make scripts safe for running in the current line based
2076 lines to make scripts safe for running in the current line based
2070 IPython.
2077 IPython.
2071 """
2078 """
2072 res = []
2079 res = []
2073 lines = script.splitlines()
2080 lines = script.splitlines()
2074 level = 0
2081 level = 0
2075
2082
2076 for l in lines:
2083 for l in lines:
2077 lstripped = l.lstrip()
2084 lstripped = l.lstrip()
2078 stripped = l.strip()
2085 stripped = l.strip()
2079 if not stripped:
2086 if not stripped:
2080 continue
2087 continue
2081 newlevel = len(l) - len(lstripped)
2088 newlevel = len(l) - len(lstripped)
2082 if level > 0 and newlevel == 0 and \
2089 if level > 0 and newlevel == 0 and \
2083 not self._is_secondary_block_start(stripped):
2090 not self._is_secondary_block_start(stripped):
2084 # add empty line
2091 # add empty line
2085 res.append('')
2092 res.append('')
2086 res.append(l)
2093 res.append(l)
2087 level = newlevel
2094 level = newlevel
2088
2095
2089 return '\n'.join(res) + '\n'
2096 return '\n'.join(res) + '\n'
2090
2097
2091 def runlines(self, lines, clean=False):
2098 def runlines(self, lines, clean=False):
2092 """Run a string of one or more lines of source.
2099 """Run a string of one or more lines of source.
2093
2100
2094 This method is capable of running a string containing multiple source
2101 This method is capable of running a string containing multiple source
2095 lines, as if they had been entered at the IPython prompt. Since it
2102 lines, as if they had been entered at the IPython prompt. Since it
2096 exposes IPython's processing machinery, the given strings can contain
2103 exposes IPython's processing machinery, the given strings can contain
2097 magic calls (%magic), special shell access (!cmd), etc.
2104 magic calls (%magic), special shell access (!cmd), etc.
2098 """
2105 """
2099
2106
2100 if isinstance(lines, (list, tuple)):
2107 if isinstance(lines, (list, tuple)):
2101 lines = '\n'.join(lines)
2108 lines = '\n'.join(lines)
2102
2109
2103 if clean:
2110 if clean:
2104 lines = self.cleanup_ipy_script(lines)
2111 lines = self.cleanup_ipy_script(lines)
2105
2112
2106 # We must start with a clean buffer, in case this is run from an
2113 # We must start with a clean buffer, in case this is run from an
2107 # interactive IPython session (via a magic, for example).
2114 # interactive IPython session (via a magic, for example).
2108 self.resetbuffer()
2115 self.resetbuffer()
2109 lines = lines.splitlines()
2116 lines = lines.splitlines()
2110 more = 0
2117 more = 0
2111
2118
2112 with nested(self.builtin_trap, self.display_trap):
2119 with nested(self.builtin_trap, self.display_trap):
2113 for line in lines:
2120 for line in lines:
2114 # skip blank lines so we don't mess up the prompt counter, but do
2121 # skip blank lines so we don't mess up the prompt counter, but do
2115 # NOT skip even a blank line if we are in a code block (more is
2122 # NOT skip even a blank line if we are in a code block (more is
2116 # true)
2123 # true)
2117
2124
2118 if line or more:
2125 if line or more:
2119 # push to raw history, so hist line numbers stay in sync
2126 # push to raw history, so hist line numbers stay in sync
2120 self.input_hist_raw.append("# " + line + "\n")
2127 self.input_hist_raw.append("# " + line + "\n")
2121 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2128 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2122 more = self.push_line(prefiltered)
2129 more = self.push_line(prefiltered)
2123 # IPython's runsource returns None if there was an error
2130 # IPython's runsource returns None if there was an error
2124 # compiling the code. This allows us to stop processing right
2131 # compiling the code. This allows us to stop processing right
2125 # away, so the user gets the error message at the right place.
2132 # away, so the user gets the error message at the right place.
2126 if more is None:
2133 if more is None:
2127 break
2134 break
2128 else:
2135 else:
2129 self.input_hist_raw.append("\n")
2136 self.input_hist_raw.append("\n")
2130 # final newline in case the input didn't have it, so that the code
2137 # final newline in case the input didn't have it, so that the code
2131 # actually does get executed
2138 # actually does get executed
2132 if more:
2139 if more:
2133 self.push_line('\n')
2140 self.push_line('\n')
2134
2141
2135 def runsource(self, source, filename='<input>', symbol='single'):
2142 def runsource(self, source, filename='<input>', symbol='single'):
2136 """Compile and run some source in the interpreter.
2143 """Compile and run some source in the interpreter.
2137
2144
2138 Arguments are as for compile_command().
2145 Arguments are as for compile_command().
2139
2146
2140 One several things can happen:
2147 One several things can happen:
2141
2148
2142 1) The input is incorrect; compile_command() raised an
2149 1) The input is incorrect; compile_command() raised an
2143 exception (SyntaxError or OverflowError). A syntax traceback
2150 exception (SyntaxError or OverflowError). A syntax traceback
2144 will be printed by calling the showsyntaxerror() method.
2151 will be printed by calling the showsyntaxerror() method.
2145
2152
2146 2) The input is incomplete, and more input is required;
2153 2) The input is incomplete, and more input is required;
2147 compile_command() returned None. Nothing happens.
2154 compile_command() returned None. Nothing happens.
2148
2155
2149 3) The input is complete; compile_command() returned a code
2156 3) The input is complete; compile_command() returned a code
2150 object. The code is executed by calling self.runcode() (which
2157 object. The code is executed by calling self.runcode() (which
2151 also handles run-time exceptions, except for SystemExit).
2158 also handles run-time exceptions, except for SystemExit).
2152
2159
2153 The return value is:
2160 The return value is:
2154
2161
2155 - True in case 2
2162 - True in case 2
2156
2163
2157 - False in the other cases, unless an exception is raised, where
2164 - False in the other cases, unless an exception is raised, where
2158 None is returned instead. This can be used by external callers to
2165 None is returned instead. This can be used by external callers to
2159 know whether to continue feeding input or not.
2166 know whether to continue feeding input or not.
2160
2167
2161 The return value can be used to decide whether to use sys.ps1 or
2168 The return value can be used to decide whether to use sys.ps1 or
2162 sys.ps2 to prompt the next line."""
2169 sys.ps2 to prompt the next line."""
2163
2170
2164 # if the source code has leading blanks, add 'if 1:\n' to it
2171 # if the source code has leading blanks, add 'if 1:\n' to it
2165 # this allows execution of indented pasted code. It is tempting
2172 # this allows execution of indented pasted code. It is tempting
2166 # to add '\n' at the end of source to run commands like ' a=1'
2173 # to add '\n' at the end of source to run commands like ' a=1'
2167 # directly, but this fails for more complicated scenarios
2174 # directly, but this fails for more complicated scenarios
2168 source=source.encode(self.stdin_encoding)
2175 source=source.encode(self.stdin_encoding)
2169 if source[:1] in [' ', '\t']:
2176 if source[:1] in [' ', '\t']:
2170 source = 'if 1:\n%s' % source
2177 source = 'if 1:\n%s' % source
2171
2178
2172 try:
2179 try:
2173 code = self.compile(source,filename,symbol)
2180 code = self.compile(source,filename,symbol)
2174 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2181 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2175 # Case 1
2182 # Case 1
2176 self.showsyntaxerror(filename)
2183 self.showsyntaxerror(filename)
2177 return None
2184 return None
2178
2185
2179 if code is None:
2186 if code is None:
2180 # Case 2
2187 # Case 2
2181 return True
2188 return True
2182
2189
2183 # Case 3
2190 # Case 3
2184 # We store the code object so that threaded shells and
2191 # We store the code object so that threaded shells and
2185 # custom exception handlers can access all this info if needed.
2192 # custom exception handlers can access all this info if needed.
2186 # The source corresponding to this can be obtained from the
2193 # The source corresponding to this can be obtained from the
2187 # buffer attribute as '\n'.join(self.buffer).
2194 # buffer attribute as '\n'.join(self.buffer).
2188 self.code_to_run = code
2195 self.code_to_run = code
2189 # now actually execute the code object
2196 # now actually execute the code object
2190 if self.runcode(code) == 0:
2197 if self.runcode(code) == 0:
2191 return False
2198 return False
2192 else:
2199 else:
2193 return None
2200 return None
2194
2201
2195 def runcode(self,code_obj):
2202 def runcode(self,code_obj):
2196 """Execute a code object.
2203 """Execute a code object.
2197
2204
2198 When an exception occurs, self.showtraceback() is called to display a
2205 When an exception occurs, self.showtraceback() is called to display a
2199 traceback.
2206 traceback.
2200
2207
2201 Return value: a flag indicating whether the code to be run completed
2208 Return value: a flag indicating whether the code to be run completed
2202 successfully:
2209 successfully:
2203
2210
2204 - 0: successful execution.
2211 - 0: successful execution.
2205 - 1: an error occurred.
2212 - 1: an error occurred.
2206 """
2213 """
2207
2214
2208 # Set our own excepthook in case the user code tries to call it
2215 # Set our own excepthook in case the user code tries to call it
2209 # directly, so that the IPython crash handler doesn't get triggered
2216 # directly, so that the IPython crash handler doesn't get triggered
2210 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2217 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2211
2218
2212 # we save the original sys.excepthook in the instance, in case config
2219 # we save the original sys.excepthook in the instance, in case config
2213 # code (such as magics) needs access to it.
2220 # code (such as magics) needs access to it.
2214 self.sys_excepthook = old_excepthook
2221 self.sys_excepthook = old_excepthook
2215 outflag = 1 # happens in more places, so it's easier as default
2222 outflag = 1 # happens in more places, so it's easier as default
2216 try:
2223 try:
2217 try:
2224 try:
2218 self.hooks.pre_runcode_hook()
2225 self.hooks.pre_runcode_hook()
2219 exec code_obj in self.user_global_ns, self.user_ns
2226 exec code_obj in self.user_global_ns, self.user_ns
2220 finally:
2227 finally:
2221 # Reset our crash handler in place
2228 # Reset our crash handler in place
2222 sys.excepthook = old_excepthook
2229 sys.excepthook = old_excepthook
2223 except SystemExit:
2230 except SystemExit:
2224 self.resetbuffer()
2231 self.resetbuffer()
2225 self.showtraceback(exception_only=True)
2232 self.showtraceback(exception_only=True)
2226 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2233 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2227 except self.custom_exceptions:
2234 except self.custom_exceptions:
2228 etype,value,tb = sys.exc_info()
2235 etype,value,tb = sys.exc_info()
2229 self.CustomTB(etype,value,tb)
2236 self.CustomTB(etype,value,tb)
2230 except:
2237 except:
2231 self.showtraceback()
2238 self.showtraceback()
2232 else:
2239 else:
2233 outflag = 0
2240 outflag = 0
2234 if softspace(sys.stdout, 0):
2241 if softspace(sys.stdout, 0):
2235 print
2242 print
2236 # Flush out code object which has been run (and source)
2243 # Flush out code object which has been run (and source)
2237 self.code_to_run = None
2244 self.code_to_run = None
2238 return outflag
2245 return outflag
2239
2246
2240 def push_line(self, line):
2247 def push_line(self, line):
2241 """Push a line to the interpreter.
2248 """Push a line to the interpreter.
2242
2249
2243 The line should not have a trailing newline; it may have
2250 The line should not have a trailing newline; it may have
2244 internal newlines. The line is appended to a buffer and the
2251 internal newlines. The line is appended to a buffer and the
2245 interpreter's runsource() method is called with the
2252 interpreter's runsource() method is called with the
2246 concatenated contents of the buffer as source. If this
2253 concatenated contents of the buffer as source. If this
2247 indicates that the command was executed or invalid, the buffer
2254 indicates that the command was executed or invalid, the buffer
2248 is reset; otherwise, the command is incomplete, and the buffer
2255 is reset; otherwise, the command is incomplete, and the buffer
2249 is left as it was after the line was appended. The return
2256 is left as it was after the line was appended. The return
2250 value is 1 if more input is required, 0 if the line was dealt
2257 value is 1 if more input is required, 0 if the line was dealt
2251 with in some way (this is the same as runsource()).
2258 with in some way (this is the same as runsource()).
2252 """
2259 """
2253
2260
2254 # autoindent management should be done here, and not in the
2261 # autoindent management should be done here, and not in the
2255 # interactive loop, since that one is only seen by keyboard input. We
2262 # interactive loop, since that one is only seen by keyboard input. We
2256 # need this done correctly even for code run via runlines (which uses
2263 # need this done correctly even for code run via runlines (which uses
2257 # push).
2264 # push).
2258
2265
2259 #print 'push line: <%s>' % line # dbg
2266 #print 'push line: <%s>' % line # dbg
2260 for subline in line.splitlines():
2267 for subline in line.splitlines():
2261 self._autoindent_update(subline)
2268 self._autoindent_update(subline)
2262 self.buffer.append(line)
2269 self.buffer.append(line)
2263 more = self.runsource('\n'.join(self.buffer), self.filename)
2270 more = self.runsource('\n'.join(self.buffer), self.filename)
2264 if not more:
2271 if not more:
2265 self.resetbuffer()
2272 self.resetbuffer()
2266 return more
2273 return more
2267
2274
2268 def _autoindent_update(self,line):
2275 def _autoindent_update(self,line):
2269 """Keep track of the indent level."""
2276 """Keep track of the indent level."""
2270
2277
2271 #debugx('line')
2278 #debugx('line')
2272 #debugx('self.indent_current_nsp')
2279 #debugx('self.indent_current_nsp')
2273 if self.autoindent:
2280 if self.autoindent:
2274 if line:
2281 if line:
2275 inisp = num_ini_spaces(line)
2282 inisp = num_ini_spaces(line)
2276 if inisp < self.indent_current_nsp:
2283 if inisp < self.indent_current_nsp:
2277 self.indent_current_nsp = inisp
2284 self.indent_current_nsp = inisp
2278
2285
2279 if line[-1] == ':':
2286 if line[-1] == ':':
2280 self.indent_current_nsp += 4
2287 self.indent_current_nsp += 4
2281 elif dedent_re.match(line):
2288 elif dedent_re.match(line):
2282 self.indent_current_nsp -= 4
2289 self.indent_current_nsp -= 4
2283 else:
2290 else:
2284 self.indent_current_nsp = 0
2291 self.indent_current_nsp = 0
2285
2292
2286 def resetbuffer(self):
2293 def resetbuffer(self):
2287 """Reset the input buffer."""
2294 """Reset the input buffer."""
2288 self.buffer[:] = []
2295 self.buffer[:] = []
2289
2296
2290 def raw_input(self,prompt='',continue_prompt=False):
2297 def raw_input(self,prompt='',continue_prompt=False):
2291 """Write a prompt and read a line.
2298 """Write a prompt and read a line.
2292
2299
2293 The returned line does not include the trailing newline.
2300 The returned line does not include the trailing newline.
2294 When the user enters the EOF key sequence, EOFError is raised.
2301 When the user enters the EOF key sequence, EOFError is raised.
2295
2302
2296 Optional inputs:
2303 Optional inputs:
2297
2304
2298 - prompt(''): a string to be printed to prompt the user.
2305 - prompt(''): a string to be printed to prompt the user.
2299
2306
2300 - continue_prompt(False): whether this line is the first one or a
2307 - continue_prompt(False): whether this line is the first one or a
2301 continuation in a sequence of inputs.
2308 continuation in a sequence of inputs.
2302 """
2309 """
2303 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2310 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2304
2311
2305 # Code run by the user may have modified the readline completer state.
2312 # Code run by the user may have modified the readline completer state.
2306 # We must ensure that our completer is back in place.
2313 # We must ensure that our completer is back in place.
2307
2314
2308 if self.has_readline:
2315 if self.has_readline:
2309 self.set_completer()
2316 self.set_completer()
2310
2317
2311 try:
2318 try:
2312 line = raw_input_original(prompt).decode(self.stdin_encoding)
2319 line = raw_input_original(prompt).decode(self.stdin_encoding)
2313 except ValueError:
2320 except ValueError:
2314 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2321 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2315 " or sys.stdout.close()!\nExiting IPython!")
2322 " or sys.stdout.close()!\nExiting IPython!")
2316 self.ask_exit()
2323 self.ask_exit()
2317 return ""
2324 return ""
2318
2325
2319 # Try to be reasonably smart about not re-indenting pasted input more
2326 # Try to be reasonably smart about not re-indenting pasted input more
2320 # than necessary. We do this by trimming out the auto-indent initial
2327 # than necessary. We do this by trimming out the auto-indent initial
2321 # spaces, if the user's actual input started itself with whitespace.
2328 # spaces, if the user's actual input started itself with whitespace.
2322 #debugx('self.buffer[-1]')
2329 #debugx('self.buffer[-1]')
2323
2330
2324 if self.autoindent:
2331 if self.autoindent:
2325 if num_ini_spaces(line) > self.indent_current_nsp:
2332 if num_ini_spaces(line) > self.indent_current_nsp:
2326 line = line[self.indent_current_nsp:]
2333 line = line[self.indent_current_nsp:]
2327 self.indent_current_nsp = 0
2334 self.indent_current_nsp = 0
2328
2335
2329 # store the unfiltered input before the user has any chance to modify
2336 # store the unfiltered input before the user has any chance to modify
2330 # it.
2337 # it.
2331 if line.strip():
2338 if line.strip():
2332 if continue_prompt:
2339 if continue_prompt:
2333 self.input_hist_raw[-1] += '%s\n' % line
2340 self.input_hist_raw[-1] += '%s\n' % line
2334 if self.has_readline and self.readline_use:
2341 if self.has_readline and self.readline_use:
2335 try:
2342 try:
2336 histlen = self.readline.get_current_history_length()
2343 histlen = self.readline.get_current_history_length()
2337 if histlen > 1:
2344 if histlen > 1:
2338 newhist = self.input_hist_raw[-1].rstrip()
2345 newhist = self.input_hist_raw[-1].rstrip()
2339 self.readline.remove_history_item(histlen-1)
2346 self.readline.remove_history_item(histlen-1)
2340 self.readline.replace_history_item(histlen-2,
2347 self.readline.replace_history_item(histlen-2,
2341 newhist.encode(self.stdin_encoding))
2348 newhist.encode(self.stdin_encoding))
2342 except AttributeError:
2349 except AttributeError:
2343 pass # re{move,place}_history_item are new in 2.4.
2350 pass # re{move,place}_history_item are new in 2.4.
2344 else:
2351 else:
2345 self.input_hist_raw.append('%s\n' % line)
2352 self.input_hist_raw.append('%s\n' % line)
2346 # only entries starting at first column go to shadow history
2353 # only entries starting at first column go to shadow history
2347 if line.lstrip() == line:
2354 if line.lstrip() == line:
2348 self.shadowhist.add(line.strip())
2355 self.shadowhist.add(line.strip())
2349 elif not continue_prompt:
2356 elif not continue_prompt:
2350 self.input_hist_raw.append('\n')
2357 self.input_hist_raw.append('\n')
2351 try:
2358 try:
2352 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2359 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2353 except:
2360 except:
2354 # blanket except, in case a user-defined prefilter crashes, so it
2361 # blanket except, in case a user-defined prefilter crashes, so it
2355 # can't take all of ipython with it.
2362 # can't take all of ipython with it.
2356 self.showtraceback()
2363 self.showtraceback()
2357 return ''
2364 return ''
2358 else:
2365 else:
2359 return lineout
2366 return lineout
2360
2367
2361 #-------------------------------------------------------------------------
2368 #-------------------------------------------------------------------------
2362 # Things related to the prefilter
2369 # Things related to the prefilter
2363 #-------------------------------------------------------------------------
2370 #-------------------------------------------------------------------------
2364
2371
2365 def init_prefilter(self):
2372 def init_prefilter(self):
2366 self.prefilter_manager = PrefilterManager(self, config=self.config)
2373 self.prefilter_manager = PrefilterManager(self, config=self.config)
2367 # Ultimately this will be refactored in the new interpreter code, but
2374 # Ultimately this will be refactored in the new interpreter code, but
2368 # for now, we should expose the main prefilter method (there's legacy
2375 # for now, we should expose the main prefilter method (there's legacy
2369 # code out there that may rely on this).
2376 # code out there that may rely on this).
2370 self.prefilter = self.prefilter_manager.prefilter_lines
2377 self.prefilter = self.prefilter_manager.prefilter_lines
2371
2378
2372 #-------------------------------------------------------------------------
2379 #-------------------------------------------------------------------------
2373 # Utilities
2380 # Utilities
2374 #-------------------------------------------------------------------------
2381 #-------------------------------------------------------------------------
2375
2382
2376 def getoutput(self, cmd):
2383 def getoutput(self, cmd):
2377 return getoutput(self.var_expand(cmd,depth=2),
2384 return getoutput(self.var_expand(cmd,depth=2),
2378 header=self.system_header,
2385 header=self.system_header,
2379 verbose=self.system_verbose)
2386 verbose=self.system_verbose)
2380
2387
2381 def getoutputerror(self, cmd):
2388 def getoutputerror(self, cmd):
2382 return getoutputerror(self.var_expand(cmd,depth=2),
2389 return getoutputerror(self.var_expand(cmd,depth=2),
2383 header=self.system_header,
2390 header=self.system_header,
2384 verbose=self.system_verbose)
2391 verbose=self.system_verbose)
2385
2392
2386 def var_expand(self,cmd,depth=0):
2393 def var_expand(self,cmd,depth=0):
2387 """Expand python variables in a string.
2394 """Expand python variables in a string.
2388
2395
2389 The depth argument indicates how many frames above the caller should
2396 The depth argument indicates how many frames above the caller should
2390 be walked to look for the local namespace where to expand variables.
2397 be walked to look for the local namespace where to expand variables.
2391
2398
2392 The global namespace for expansion is always the user's interactive
2399 The global namespace for expansion is always the user's interactive
2393 namespace.
2400 namespace.
2394 """
2401 """
2395
2402
2396 return str(ItplNS(cmd,
2403 return str(ItplNS(cmd,
2397 self.user_ns, # globals
2404 self.user_ns, # globals
2398 # Skip our own frame in searching for locals:
2405 # Skip our own frame in searching for locals:
2399 sys._getframe(depth+1).f_locals # locals
2406 sys._getframe(depth+1).f_locals # locals
2400 ))
2407 ))
2401
2408
2402 def mktempfile(self,data=None):
2409 def mktempfile(self,data=None):
2403 """Make a new tempfile and return its filename.
2410 """Make a new tempfile and return its filename.
2404
2411
2405 This makes a call to tempfile.mktemp, but it registers the created
2412 This makes a call to tempfile.mktemp, but it registers the created
2406 filename internally so ipython cleans it up at exit time.
2413 filename internally so ipython cleans it up at exit time.
2407
2414
2408 Optional inputs:
2415 Optional inputs:
2409
2416
2410 - data(None): if data is given, it gets written out to the temp file
2417 - data(None): if data is given, it gets written out to the temp file
2411 immediately, and the file is closed again."""
2418 immediately, and the file is closed again."""
2412
2419
2413 filename = tempfile.mktemp('.py','ipython_edit_')
2420 filename = tempfile.mktemp('.py','ipython_edit_')
2414 self.tempfiles.append(filename)
2421 self.tempfiles.append(filename)
2415
2422
2416 if data:
2423 if data:
2417 tmp_file = open(filename,'w')
2424 tmp_file = open(filename,'w')
2418 tmp_file.write(data)
2425 tmp_file.write(data)
2419 tmp_file.close()
2426 tmp_file.close()
2420 return filename
2427 return filename
2421
2428
2422 def write(self,data):
2429 def write(self,data):
2423 """Write a string to the default output"""
2430 """Write a string to the default output"""
2424 Term.cout.write(data)
2431 Term.cout.write(data)
2425
2432
2426 def write_err(self,data):
2433 def write_err(self,data):
2427 """Write a string to the default error output"""
2434 """Write a string to the default error output"""
2428 Term.cerr.write(data)
2435 Term.cerr.write(data)
2429
2436
2430 def ask_yes_no(self,prompt,default=True):
2437 def ask_yes_no(self,prompt,default=True):
2431 if self.quiet:
2438 if self.quiet:
2432 return True
2439 return True
2433 return ask_yes_no(prompt,default)
2440 return ask_yes_no(prompt,default)
2434
2441
2435 #-------------------------------------------------------------------------
2442 #-------------------------------------------------------------------------
2436 # Things related to GUI support and pylab
2443 # Things related to GUI support and pylab
2437 #-------------------------------------------------------------------------
2444 #-------------------------------------------------------------------------
2438
2445
2439 def enable_pylab(self, gui=None):
2446 def enable_pylab(self, gui=None):
2440 """Activate pylab support at runtime.
2447 """Activate pylab support at runtime.
2441
2448
2442 This turns on support for matplotlib, preloads into the interactive
2449 This turns on support for matplotlib, preloads into the interactive
2443 namespace all of numpy and pylab, and configures IPython to correcdtly
2450 namespace all of numpy and pylab, and configures IPython to correcdtly
2444 interact with the GUI event loop. The GUI backend to be used can be
2451 interact with the GUI event loop. The GUI backend to be used can be
2445 optionally selected with the optional :param:`gui` argument.
2452 optionally selected with the optional :param:`gui` argument.
2446
2453
2447 Parameters
2454 Parameters
2448 ----------
2455 ----------
2449 gui : optional, string
2456 gui : optional, string
2450
2457
2451 If given, dictates the choice of matplotlib GUI backend to use
2458 If given, dictates the choice of matplotlib GUI backend to use
2452 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2459 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2453 'gtk'), otherwise we use the default chosen by matplotlib (as
2460 'gtk'), otherwise we use the default chosen by matplotlib (as
2454 dictated by the matplotlib build-time options plus the user's
2461 dictated by the matplotlib build-time options plus the user's
2455 matplotlibrc configuration file).
2462 matplotlibrc configuration file).
2456 """
2463 """
2457 # We want to prevent the loading of pylab to pollute the user's
2464 # We want to prevent the loading of pylab to pollute the user's
2458 # namespace as shown by the %who* magics, so we execute the activation
2465 # namespace as shown by the %who* magics, so we execute the activation
2459 # code in an empty namespace, and we update *both* user_ns and
2466 # code in an empty namespace, and we update *both* user_ns and
2460 # user_ns_hidden with this information.
2467 # user_ns_hidden with this information.
2461 ns = {}
2468 ns = {}
2462 gui = pylab_activate(ns, gui)
2469 gui = pylab_activate(ns, gui)
2463 self.user_ns.update(ns)
2470 self.user_ns.update(ns)
2464 self.user_ns_hidden.update(ns)
2471 self.user_ns_hidden.update(ns)
2465 # Now we must activate the gui pylab wants to use, and fix %run to take
2472 # Now we must activate the gui pylab wants to use, and fix %run to take
2466 # plot updates into account
2473 # plot updates into account
2467 enable_gui(gui)
2474 enable_gui(gui)
2468 self.magic_run = self._pylab_magic_run
2475 self.magic_run = self._pylab_magic_run
2469
2476
2470 #-------------------------------------------------------------------------
2477 #-------------------------------------------------------------------------
2471 # Things related to IPython exiting
2478 # Things related to IPython exiting
2472 #-------------------------------------------------------------------------
2479 #-------------------------------------------------------------------------
2473
2480
2474 def ask_exit(self):
2481 def ask_exit(self):
2475 """ Ask the shell to exit. Can be overiden and used as a callback. """
2482 """ Ask the shell to exit. Can be overiden and used as a callback. """
2476 self.exit_now = True
2483 self.exit_now = True
2477
2484
2478 def exit(self):
2485 def exit(self):
2479 """Handle interactive exit.
2486 """Handle interactive exit.
2480
2487
2481 This method calls the ask_exit callback."""
2488 This method calls the ask_exit callback."""
2482 if self.confirm_exit:
2489 if self.confirm_exit:
2483 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2490 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2484 self.ask_exit()
2491 self.ask_exit()
2485 else:
2492 else:
2486 self.ask_exit()
2493 self.ask_exit()
2487
2494
2488 def atexit_operations(self):
2495 def atexit_operations(self):
2489 """This will be executed at the time of exit.
2496 """This will be executed at the time of exit.
2490
2497
2491 Saving of persistent data should be performed here.
2498 Saving of persistent data should be performed here.
2492 """
2499 """
2493 self.savehist()
2500 self.savehist()
2494
2501
2495 # Cleanup all tempfiles left around
2502 # Cleanup all tempfiles left around
2496 for tfile in self.tempfiles:
2503 for tfile in self.tempfiles:
2497 try:
2504 try:
2498 os.unlink(tfile)
2505 os.unlink(tfile)
2499 except OSError:
2506 except OSError:
2500 pass
2507 pass
2501
2508
2502 # Clear all user namespaces to release all references cleanly.
2509 # Clear all user namespaces to release all references cleanly.
2503 self.reset()
2510 self.reset()
2504
2511
2505 # Run user hooks
2512 # Run user hooks
2506 self.hooks.shutdown_hook()
2513 self.hooks.shutdown_hook()
2507
2514
2508 def cleanup(self):
2515 def cleanup(self):
2509 self.restore_sys_module_state()
2516 self.restore_sys_module_state()
2510
2517
2511
2518
2519 class InteractiveShellABC(object):
2520 """An abstract base class for InteractiveShell."""
2521 __metaclass__ = abc.ABCMeta
2522
2523 InteractiveShellABC.register(InteractiveShell)
@@ -1,1016 +1,1016 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import re
30 import re
31
31
32 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
33 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core.splitinput import split_user_input
35 from IPython.core.splitinput import split_user_input
36 from IPython.core.page import page
36 from IPython.core.page import page
37
37
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.io import Term
39 from IPython.utils.io import Term
40 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Global utilities, errors and constants
44 # Global utilities, errors and constants
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
48 # are updated in a number of places. Not great, but at least we told you.
48 # are updated in a number of places. Not great, but at least we told you.
49 ESC_SHELL = '!'
49 ESC_SHELL = '!'
50 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
51 ESC_HELP = '?'
51 ESC_HELP = '?'
52 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
53 ESC_QUOTE = ','
53 ESC_QUOTE = ','
54 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
55 ESC_PAREN = '/'
55 ESC_PAREN = '/'
56
56
57
57
58 class PrefilterError(Exception):
58 class PrefilterError(Exception):
59 pass
59 pass
60
60
61
61
62 # RegExp to identify potential function names
62 # RegExp to identify potential function names
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64
64
65 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
66 # particular, all binary operators should be excluded, so that if foo is
66 # particular, all binary operators should be excluded, so that if foo is
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
70 # existing names.
70 # existing names.
71
71
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
76
76
77 # try to catch also methods for stuff in lists/tuples/dicts: off
77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
79 # to be modified so it wouldn't break things at '['. That line is
79 # to be modified so it wouldn't break things at '['. That line is
80 # nasty enough that I shouldn't change it until I can test it _well_.
80 # nasty enough that I shouldn't change it until I can test it _well_.
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82
82
83
83
84 # Handler Check Utilities
84 # Handler Check Utilities
85 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
86 """Is the given identifier defined in one of the namespaces which shadow
86 """Is the given identifier defined in one of the namespaces which shadow
87 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
88 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
89 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
90 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
91 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
92 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
93
93
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # The LineInfo class used throughout
96 # The LineInfo class used throughout
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98
98
99
99
100 class LineInfo(object):
100 class LineInfo(object):
101 """A single line of input and associated info.
101 """A single line of input and associated info.
102
102
103 Includes the following as properties:
103 Includes the following as properties:
104
104
105 line
105 line
106 The original, raw line
106 The original, raw line
107
107
108 continue_prompt
108 continue_prompt
109 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
110
110
111 pre
111 pre
112 The initial esc character or whitespace.
112 The initial esc character or whitespace.
113
113
114 pre_char
114 pre_char
115 The escape character(s) in pre or the empty string if there isn't one.
115 The escape character(s) in pre or the empty string if there isn't one.
116 Note that '!!' is a possible value for pre_char. Otherwise it will
116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 always be a single character.
117 always be a single character.
118
118
119 pre_whitespace
119 pre_whitespace
120 The leading whitespace from pre if it exists. If there is a pre_char,
120 The leading whitespace from pre if it exists. If there is a pre_char,
121 this is just ''.
121 this is just ''.
122
122
123 ifun
123 ifun
124 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
125 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
126 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
127 etc.
127 etc.
128
128
129 the_rest
129 the_rest
130 Everything else on the line.
130 Everything else on the line.
131 """
131 """
132 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
133 self.line = line
133 self.line = line
134 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136
136
137 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
138 if self.pre_char:
138 if self.pre_char:
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 else:
140 else:
141 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
142
142
143 self._oinfo = None
143 self._oinfo = None
144
144
145 def ofind(self, ip):
145 def ofind(self, ip):
146 """Do a full, attribute-walking lookup of the ifun in the various
146 """Do a full, attribute-walking lookup of the ifun in the various
147 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
148
148
149 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
150
150
151 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
152 only be run if autocall is on and if the line hasn't matched any
152 only be run if autocall is on and if the line hasn't matched any
153 other, less dangerous handlers.
153 other, less dangerous handlers.
154
154
155 Does cache the results of the call, so can be called multiple times
155 Does cache the results of the call, so can be called multiple times
156 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
157 """
157 """
158 if not self._oinfo:
158 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
159 # ip.shell._ofind is actually on the Magic class!
160 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
161 return self._oinfo
161 return self._oinfo
162
162
163 def __str__(self):
163 def __str__(self):
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165
165
166
166
167 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
168 # Main Prefilter manager
168 # Main Prefilter manager
169 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
170
170
171
171
172 class PrefilterManager(Configurable):
172 class PrefilterManager(Configurable):
173 """Main prefilter component.
173 """Main prefilter component.
174
174
175 The IPython prefilter is run on all user input before it is run. The
175 The IPython prefilter is run on all user input before it is run. The
176 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
177 input.
177 input.
178
178
179 The iplementation consists of two phases:
179 The iplementation consists of two phases:
180
180
181 1. Transformers
181 1. Transformers
182 2. Checkers and handlers
182 2. Checkers and handlers
183
183
184 Over time, we plan on deprecating the checkers and handlers and doing
184 Over time, we plan on deprecating the checkers and handlers and doing
185 everything in the transformers.
185 everything in the transformers.
186
186
187 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
188 a single method :meth:`transform` that takes a line and returns a
188 a single method :meth:`transform` that takes a line and returns a
189 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
190 tool, but our current ones use regular expressions for speed. We also
190 tool, but our current ones use regular expressions for speed. We also
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192
192
193 After all the transformers have been run, the line is fed to the checkers,
193 After all the transformers have been run, the line is fed to the checkers,
194 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 the line is passed to the :meth:`handle` method of the returned
198 the line is passed to the :meth:`handle` method of the returned
199 handler and no further checkers are tried.
199 handler and no further checkers are tried.
200
200
201 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
202 the order in which they are called. Smaller priorities are tried first.
202 the order in which they are called. Smaller priorities are tried first.
203
203
204 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
205 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
206
206
207 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
208 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
210 """
210 """
211
211
212 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
213 shell = Instance('IPython.core.iplib.InteractiveShell')
213 shell = Instance('IPython.core.iplib.InteractiveShellABC')
214
214
215 def __init__(self, shell, config=None):
215 def __init__(self, shell, config=None):
216 super(PrefilterManager, self).__init__(config=config)
216 super(PrefilterManager, self).__init__(config=config)
217 self.shell = shell
217 self.shell = shell
218 self.init_transformers()
218 self.init_transformers()
219 self.init_handlers()
219 self.init_handlers()
220 self.init_checkers()
220 self.init_checkers()
221
221
222 #-------------------------------------------------------------------------
222 #-------------------------------------------------------------------------
223 # API for managing transformers
223 # API for managing transformers
224 #-------------------------------------------------------------------------
224 #-------------------------------------------------------------------------
225
225
226 def init_transformers(self):
226 def init_transformers(self):
227 """Create the default transformers."""
227 """Create the default transformers."""
228 self._transformers = []
228 self._transformers = []
229 for transformer_cls in _default_transformers:
229 for transformer_cls in _default_transformers:
230 transformer_cls(self.shell, self, config=self.config)
230 transformer_cls(self.shell, self, config=self.config)
231
231
232 def sort_transformers(self):
232 def sort_transformers(self):
233 """Sort the transformers by priority.
233 """Sort the transformers by priority.
234
234
235 This must be called after the priority of a transformer is changed.
235 This must be called after the priority of a transformer is changed.
236 The :meth:`register_transformer` method calls this automatically.
236 The :meth:`register_transformer` method calls this automatically.
237 """
237 """
238 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
238 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
239
239
240 @property
240 @property
241 def transformers(self):
241 def transformers(self):
242 """Return a list of checkers, sorted by priority."""
242 """Return a list of checkers, sorted by priority."""
243 return self._transformers
243 return self._transformers
244
244
245 def register_transformer(self, transformer):
245 def register_transformer(self, transformer):
246 """Register a transformer instance."""
246 """Register a transformer instance."""
247 if transformer not in self._transformers:
247 if transformer not in self._transformers:
248 self._transformers.append(transformer)
248 self._transformers.append(transformer)
249 self.sort_transformers()
249 self.sort_transformers()
250
250
251 def unregister_transformer(self, transformer):
251 def unregister_transformer(self, transformer):
252 """Unregister a transformer instance."""
252 """Unregister a transformer instance."""
253 if transformer in self._transformers:
253 if transformer in self._transformers:
254 self._transformers.remove(transformer)
254 self._transformers.remove(transformer)
255
255
256 #-------------------------------------------------------------------------
256 #-------------------------------------------------------------------------
257 # API for managing checkers
257 # API for managing checkers
258 #-------------------------------------------------------------------------
258 #-------------------------------------------------------------------------
259
259
260 def init_checkers(self):
260 def init_checkers(self):
261 """Create the default checkers."""
261 """Create the default checkers."""
262 self._checkers = []
262 self._checkers = []
263 for checker in _default_checkers:
263 for checker in _default_checkers:
264 checker(self.shell, self, config=self.config)
264 checker(self.shell, self, config=self.config)
265
265
266 def sort_checkers(self):
266 def sort_checkers(self):
267 """Sort the checkers by priority.
267 """Sort the checkers by priority.
268
268
269 This must be called after the priority of a checker is changed.
269 This must be called after the priority of a checker is changed.
270 The :meth:`register_checker` method calls this automatically.
270 The :meth:`register_checker` method calls this automatically.
271 """
271 """
272 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
272 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
273
273
274 @property
274 @property
275 def checkers(self):
275 def checkers(self):
276 """Return a list of checkers, sorted by priority."""
276 """Return a list of checkers, sorted by priority."""
277 return self._checkers
277 return self._checkers
278
278
279 def register_checker(self, checker):
279 def register_checker(self, checker):
280 """Register a checker instance."""
280 """Register a checker instance."""
281 if checker not in self._checkers:
281 if checker not in self._checkers:
282 self._checkers.append(checker)
282 self._checkers.append(checker)
283 self.sort_checkers()
283 self.sort_checkers()
284
284
285 def unregister_checker(self, checker):
285 def unregister_checker(self, checker):
286 """Unregister a checker instance."""
286 """Unregister a checker instance."""
287 if checker in self._checkers:
287 if checker in self._checkers:
288 self._checkers.remove(checker)
288 self._checkers.remove(checker)
289
289
290 #-------------------------------------------------------------------------
290 #-------------------------------------------------------------------------
291 # API for managing checkers
291 # API for managing checkers
292 #-------------------------------------------------------------------------
292 #-------------------------------------------------------------------------
293
293
294 def init_handlers(self):
294 def init_handlers(self):
295 """Create the default handlers."""
295 """Create the default handlers."""
296 self._handlers = {}
296 self._handlers = {}
297 self._esc_handlers = {}
297 self._esc_handlers = {}
298 for handler in _default_handlers:
298 for handler in _default_handlers:
299 handler(self.shell, self, config=self.config)
299 handler(self.shell, self, config=self.config)
300
300
301 @property
301 @property
302 def handlers(self):
302 def handlers(self):
303 """Return a dict of all the handlers."""
303 """Return a dict of all the handlers."""
304 return self._handlers
304 return self._handlers
305
305
306 def register_handler(self, name, handler, esc_strings):
306 def register_handler(self, name, handler, esc_strings):
307 """Register a handler instance by name with esc_strings."""
307 """Register a handler instance by name with esc_strings."""
308 self._handlers[name] = handler
308 self._handlers[name] = handler
309 for esc_str in esc_strings:
309 for esc_str in esc_strings:
310 self._esc_handlers[esc_str] = handler
310 self._esc_handlers[esc_str] = handler
311
311
312 def unregister_handler(self, name, handler, esc_strings):
312 def unregister_handler(self, name, handler, esc_strings):
313 """Unregister a handler instance by name with esc_strings."""
313 """Unregister a handler instance by name with esc_strings."""
314 try:
314 try:
315 del self._handlers[name]
315 del self._handlers[name]
316 except KeyError:
316 except KeyError:
317 pass
317 pass
318 for esc_str in esc_strings:
318 for esc_str in esc_strings:
319 h = self._esc_handlers.get(esc_str)
319 h = self._esc_handlers.get(esc_str)
320 if h is handler:
320 if h is handler:
321 del self._esc_handlers[esc_str]
321 del self._esc_handlers[esc_str]
322
322
323 def get_handler_by_name(self, name):
323 def get_handler_by_name(self, name):
324 """Get a handler by its name."""
324 """Get a handler by its name."""
325 return self._handlers.get(name)
325 return self._handlers.get(name)
326
326
327 def get_handler_by_esc(self, esc_str):
327 def get_handler_by_esc(self, esc_str):
328 """Get a handler by its escape string."""
328 """Get a handler by its escape string."""
329 return self._esc_handlers.get(esc_str)
329 return self._esc_handlers.get(esc_str)
330
330
331 #-------------------------------------------------------------------------
331 #-------------------------------------------------------------------------
332 # Main prefiltering API
332 # Main prefiltering API
333 #-------------------------------------------------------------------------
333 #-------------------------------------------------------------------------
334
334
335 def prefilter_line_info(self, line_info):
335 def prefilter_line_info(self, line_info):
336 """Prefilter a line that has been converted to a LineInfo object.
336 """Prefilter a line that has been converted to a LineInfo object.
337
337
338 This implements the checker/handler part of the prefilter pipe.
338 This implements the checker/handler part of the prefilter pipe.
339 """
339 """
340 # print "prefilter_line_info: ", line_info
340 # print "prefilter_line_info: ", line_info
341 handler = self.find_handler(line_info)
341 handler = self.find_handler(line_info)
342 return handler.handle(line_info)
342 return handler.handle(line_info)
343
343
344 def find_handler(self, line_info):
344 def find_handler(self, line_info):
345 """Find a handler for the line_info by trying checkers."""
345 """Find a handler for the line_info by trying checkers."""
346 for checker in self.checkers:
346 for checker in self.checkers:
347 if checker.enabled:
347 if checker.enabled:
348 handler = checker.check(line_info)
348 handler = checker.check(line_info)
349 if handler:
349 if handler:
350 return handler
350 return handler
351 return self.get_handler_by_name('normal')
351 return self.get_handler_by_name('normal')
352
352
353 def transform_line(self, line, continue_prompt):
353 def transform_line(self, line, continue_prompt):
354 """Calls the enabled transformers in order of increasing priority."""
354 """Calls the enabled transformers in order of increasing priority."""
355 for transformer in self.transformers:
355 for transformer in self.transformers:
356 if transformer.enabled:
356 if transformer.enabled:
357 line = transformer.transform(line, continue_prompt)
357 line = transformer.transform(line, continue_prompt)
358 return line
358 return line
359
359
360 def prefilter_line(self, line, continue_prompt=False):
360 def prefilter_line(self, line, continue_prompt=False):
361 """Prefilter a single input line as text.
361 """Prefilter a single input line as text.
362
362
363 This method prefilters a single line of text by calling the
363 This method prefilters a single line of text by calling the
364 transformers and then the checkers/handlers.
364 transformers and then the checkers/handlers.
365 """
365 """
366
366
367 # print "prefilter_line: ", line, continue_prompt
367 # print "prefilter_line: ", line, continue_prompt
368 # All handlers *must* return a value, even if it's blank ('').
368 # All handlers *must* return a value, even if it's blank ('').
369
369
370 # Lines are NOT logged here. Handlers should process the line as
370 # Lines are NOT logged here. Handlers should process the line as
371 # needed, update the cache AND log it (so that the input cache array
371 # needed, update the cache AND log it (so that the input cache array
372 # stays synced).
372 # stays synced).
373
373
374 # save the line away in case we crash, so the post-mortem handler can
374 # save the line away in case we crash, so the post-mortem handler can
375 # record it
375 # record it
376 self.shell._last_input_line = line
376 self.shell._last_input_line = line
377
377
378 if not line:
378 if not line:
379 # Return immediately on purely empty lines, so that if the user
379 # Return immediately on purely empty lines, so that if the user
380 # previously typed some whitespace that started a continuation
380 # previously typed some whitespace that started a continuation
381 # prompt, he can break out of that loop with just an empty line.
381 # prompt, he can break out of that loop with just an empty line.
382 # This is how the default python prompt works.
382 # This is how the default python prompt works.
383
383
384 # Only return if the accumulated input buffer was just whitespace!
384 # Only return if the accumulated input buffer was just whitespace!
385 if ''.join(self.shell.buffer).isspace():
385 if ''.join(self.shell.buffer).isspace():
386 self.shell.buffer[:] = []
386 self.shell.buffer[:] = []
387 return ''
387 return ''
388
388
389 # At this point, we invoke our transformers.
389 # At this point, we invoke our transformers.
390 if not continue_prompt or (continue_prompt and self.multi_line_specials):
390 if not continue_prompt or (continue_prompt and self.multi_line_specials):
391 line = self.transform_line(line, continue_prompt)
391 line = self.transform_line(line, continue_prompt)
392
392
393 # Now we compute line_info for the checkers and handlers
393 # Now we compute line_info for the checkers and handlers
394 line_info = LineInfo(line, continue_prompt)
394 line_info = LineInfo(line, continue_prompt)
395
395
396 # the input history needs to track even empty lines
396 # the input history needs to track even empty lines
397 stripped = line.strip()
397 stripped = line.strip()
398
398
399 normal_handler = self.get_handler_by_name('normal')
399 normal_handler = self.get_handler_by_name('normal')
400 if not stripped:
400 if not stripped:
401 if not continue_prompt:
401 if not continue_prompt:
402 self.shell.outputcache.prompt_count -= 1
402 self.shell.outputcache.prompt_count -= 1
403
403
404 return normal_handler.handle(line_info)
404 return normal_handler.handle(line_info)
405
405
406 # special handlers are only allowed for single line statements
406 # special handlers are only allowed for single line statements
407 if continue_prompt and not self.multi_line_specials:
407 if continue_prompt and not self.multi_line_specials:
408 return normal_handler.handle(line_info)
408 return normal_handler.handle(line_info)
409
409
410 prefiltered = self.prefilter_line_info(line_info)
410 prefiltered = self.prefilter_line_info(line_info)
411 # print "prefiltered line: %r" % prefiltered
411 # print "prefiltered line: %r" % prefiltered
412 return prefiltered
412 return prefiltered
413
413
414 def prefilter_lines(self, lines, continue_prompt=False):
414 def prefilter_lines(self, lines, continue_prompt=False):
415 """Prefilter multiple input lines of text.
415 """Prefilter multiple input lines of text.
416
416
417 This is the main entry point for prefiltering multiple lines of
417 This is the main entry point for prefiltering multiple lines of
418 input. This simply calls :meth:`prefilter_line` for each line of
418 input. This simply calls :meth:`prefilter_line` for each line of
419 input.
419 input.
420
420
421 This covers cases where there are multiple lines in the user entry,
421 This covers cases where there are multiple lines in the user entry,
422 which is the case when the user goes back to a multiline history
422 which is the case when the user goes back to a multiline history
423 entry and presses enter.
423 entry and presses enter.
424 """
424 """
425 llines = lines.rstrip('\n').split('\n')
425 llines = lines.rstrip('\n').split('\n')
426 # We can get multiple lines in one shot, where multiline input 'blends'
426 # We can get multiple lines in one shot, where multiline input 'blends'
427 # into one line, in cases like recalling from the readline history
427 # into one line, in cases like recalling from the readline history
428 # buffer. We need to make sure that in such cases, we correctly
428 # buffer. We need to make sure that in such cases, we correctly
429 # communicate downstream which line is first and which are continuation
429 # communicate downstream which line is first and which are continuation
430 # ones.
430 # ones.
431 if len(llines) > 1:
431 if len(llines) > 1:
432 out = '\n'.join([self.prefilter_line(line, lnum>0)
432 out = '\n'.join([self.prefilter_line(line, lnum>0)
433 for lnum, line in enumerate(llines) ])
433 for lnum, line in enumerate(llines) ])
434 else:
434 else:
435 out = self.prefilter_line(llines[0], continue_prompt)
435 out = self.prefilter_line(llines[0], continue_prompt)
436
436
437 return out
437 return out
438
438
439 #-----------------------------------------------------------------------------
439 #-----------------------------------------------------------------------------
440 # Prefilter transformers
440 # Prefilter transformers
441 #-----------------------------------------------------------------------------
441 #-----------------------------------------------------------------------------
442
442
443
443
444 class PrefilterTransformer(Configurable):
444 class PrefilterTransformer(Configurable):
445 """Transform a line of user input."""
445 """Transform a line of user input."""
446
446
447 priority = Int(100, config=True)
447 priority = Int(100, config=True)
448 # Transformers don't currently use shell or prefilter_manager, but as we
448 # Transformers don't currently use shell or prefilter_manager, but as we
449 # move away from checkers and handlers, they will need them.
449 # move away from checkers and handlers, they will need them.
450 shell = Instance('IPython.core.iplib.InteractiveShell')
450 shell = Instance('IPython.core.iplib.InteractiveShellABC')
451 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
451 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
452 enabled = Bool(True, config=True)
452 enabled = Bool(True, config=True)
453
453
454 def __init__(self, shell, prefilter_manager, config=None):
454 def __init__(self, shell, prefilter_manager, config=None):
455 super(PrefilterTransformer, self).__init__(config=config)
455 super(PrefilterTransformer, self).__init__(config=config)
456 self.shell = shell
456 self.shell = shell
457 self.prefilter_manager = prefilter_manager
457 self.prefilter_manager = prefilter_manager
458 self.prefilter_manager.register_transformer(self)
458 self.prefilter_manager.register_transformer(self)
459
459
460 def transform(self, line, continue_prompt):
460 def transform(self, line, continue_prompt):
461 """Transform a line, returning the new one."""
461 """Transform a line, returning the new one."""
462 return None
462 return None
463
463
464 def __repr__(self):
464 def __repr__(self):
465 return "<%s(priority=%r, enabled=%r)>" % (
465 return "<%s(priority=%r, enabled=%r)>" % (
466 self.__class__.__name__, self.priority, self.enabled)
466 self.__class__.__name__, self.priority, self.enabled)
467
467
468
468
469 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
469 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
470 r'\s*=\s*!(?P<cmd>.*)')
470 r'\s*=\s*!(?P<cmd>.*)')
471
471
472
472
473 class AssignSystemTransformer(PrefilterTransformer):
473 class AssignSystemTransformer(PrefilterTransformer):
474 """Handle the `files = !ls` syntax."""
474 """Handle the `files = !ls` syntax."""
475
475
476 priority = Int(100, config=True)
476 priority = Int(100, config=True)
477
477
478 def transform(self, line, continue_prompt):
478 def transform(self, line, continue_prompt):
479 m = _assign_system_re.match(line)
479 m = _assign_system_re.match(line)
480 if m is not None:
480 if m is not None:
481 cmd = m.group('cmd')
481 cmd = m.group('cmd')
482 lhs = m.group('lhs')
482 lhs = m.group('lhs')
483 expr = make_quoted_expr("sc -l =%s" % cmd)
483 expr = make_quoted_expr("sc -l =%s" % cmd)
484 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
484 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
485 return new_line
485 return new_line
486 return line
486 return line
487
487
488
488
489 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
489 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
490 r'\s*=\s*%(?P<cmd>.*)')
490 r'\s*=\s*%(?P<cmd>.*)')
491
491
492 class AssignMagicTransformer(PrefilterTransformer):
492 class AssignMagicTransformer(PrefilterTransformer):
493 """Handle the `a = %who` syntax."""
493 """Handle the `a = %who` syntax."""
494
494
495 priority = Int(200, config=True)
495 priority = Int(200, config=True)
496
496
497 def transform(self, line, continue_prompt):
497 def transform(self, line, continue_prompt):
498 m = _assign_magic_re.match(line)
498 m = _assign_magic_re.match(line)
499 if m is not None:
499 if m is not None:
500 cmd = m.group('cmd')
500 cmd = m.group('cmd')
501 lhs = m.group('lhs')
501 lhs = m.group('lhs')
502 expr = make_quoted_expr(cmd)
502 expr = make_quoted_expr(cmd)
503 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
503 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
504 return new_line
504 return new_line
505 return line
505 return line
506
506
507
507
508 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
508 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
509
509
510 class PyPromptTransformer(PrefilterTransformer):
510 class PyPromptTransformer(PrefilterTransformer):
511 """Handle inputs that start with '>>> ' syntax."""
511 """Handle inputs that start with '>>> ' syntax."""
512
512
513 priority = Int(50, config=True)
513 priority = Int(50, config=True)
514
514
515 def transform(self, line, continue_prompt):
515 def transform(self, line, continue_prompt):
516
516
517 if not line or line.isspace() or line.strip() == '...':
517 if not line or line.isspace() or line.strip() == '...':
518 # This allows us to recognize multiple input prompts separated by
518 # This allows us to recognize multiple input prompts separated by
519 # blank lines and pasted in a single chunk, very common when
519 # blank lines and pasted in a single chunk, very common when
520 # pasting doctests or long tutorial passages.
520 # pasting doctests or long tutorial passages.
521 return ''
521 return ''
522 m = _classic_prompt_re.match(line)
522 m = _classic_prompt_re.match(line)
523 if m:
523 if m:
524 return line[len(m.group(0)):]
524 return line[len(m.group(0)):]
525 else:
525 else:
526 return line
526 return line
527
527
528
528
529 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
529 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
530
530
531 class IPyPromptTransformer(PrefilterTransformer):
531 class IPyPromptTransformer(PrefilterTransformer):
532 """Handle inputs that start classic IPython prompt syntax."""
532 """Handle inputs that start classic IPython prompt syntax."""
533
533
534 priority = Int(50, config=True)
534 priority = Int(50, config=True)
535
535
536 def transform(self, line, continue_prompt):
536 def transform(self, line, continue_prompt):
537
537
538 if not line or line.isspace() or line.strip() == '...':
538 if not line or line.isspace() or line.strip() == '...':
539 # This allows us to recognize multiple input prompts separated by
539 # This allows us to recognize multiple input prompts separated by
540 # blank lines and pasted in a single chunk, very common when
540 # blank lines and pasted in a single chunk, very common when
541 # pasting doctests or long tutorial passages.
541 # pasting doctests or long tutorial passages.
542 return ''
542 return ''
543 m = _ipy_prompt_re.match(line)
543 m = _ipy_prompt_re.match(line)
544 if m:
544 if m:
545 return line[len(m.group(0)):]
545 return line[len(m.group(0)):]
546 else:
546 else:
547 return line
547 return line
548
548
549 #-----------------------------------------------------------------------------
549 #-----------------------------------------------------------------------------
550 # Prefilter checkers
550 # Prefilter checkers
551 #-----------------------------------------------------------------------------
551 #-----------------------------------------------------------------------------
552
552
553
553
554 class PrefilterChecker(Configurable):
554 class PrefilterChecker(Configurable):
555 """Inspect an input line and return a handler for that line."""
555 """Inspect an input line and return a handler for that line."""
556
556
557 priority = Int(100, config=True)
557 priority = Int(100, config=True)
558 shell = Instance('IPython.core.iplib.InteractiveShell')
558 shell = Instance('IPython.core.iplib.InteractiveShellABC')
559 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
559 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
560 enabled = Bool(True, config=True)
560 enabled = Bool(True, config=True)
561
561
562 def __init__(self, shell, prefilter_manager, config=None):
562 def __init__(self, shell, prefilter_manager, config=None):
563 super(PrefilterChecker, self).__init__(config=config)
563 super(PrefilterChecker, self).__init__(config=config)
564 self.shell = shell
564 self.shell = shell
565 self.prefilter_manager = prefilter_manager
565 self.prefilter_manager = prefilter_manager
566 self.prefilter_manager.register_checker(self)
566 self.prefilter_manager.register_checker(self)
567
567
568 def check(self, line_info):
568 def check(self, line_info):
569 """Inspect line_info and return a handler instance or None."""
569 """Inspect line_info and return a handler instance or None."""
570 return None
570 return None
571
571
572 def __repr__(self):
572 def __repr__(self):
573 return "<%s(priority=%r, enabled=%r)>" % (
573 return "<%s(priority=%r, enabled=%r)>" % (
574 self.__class__.__name__, self.priority, self.enabled)
574 self.__class__.__name__, self.priority, self.enabled)
575
575
576
576
577 class EmacsChecker(PrefilterChecker):
577 class EmacsChecker(PrefilterChecker):
578
578
579 priority = Int(100, config=True)
579 priority = Int(100, config=True)
580 enabled = Bool(False, config=True)
580 enabled = Bool(False, config=True)
581
581
582 def check(self, line_info):
582 def check(self, line_info):
583 "Emacs ipython-mode tags certain input lines."
583 "Emacs ipython-mode tags certain input lines."
584 if line_info.line.endswith('# PYTHON-MODE'):
584 if line_info.line.endswith('# PYTHON-MODE'):
585 return self.prefilter_manager.get_handler_by_name('emacs')
585 return self.prefilter_manager.get_handler_by_name('emacs')
586 else:
586 else:
587 return None
587 return None
588
588
589
589
590 class ShellEscapeChecker(PrefilterChecker):
590 class ShellEscapeChecker(PrefilterChecker):
591
591
592 priority = Int(200, config=True)
592 priority = Int(200, config=True)
593
593
594 def check(self, line_info):
594 def check(self, line_info):
595 if line_info.line.lstrip().startswith(ESC_SHELL):
595 if line_info.line.lstrip().startswith(ESC_SHELL):
596 return self.prefilter_manager.get_handler_by_name('shell')
596 return self.prefilter_manager.get_handler_by_name('shell')
597
597
598
598
599 class IPyAutocallChecker(PrefilterChecker):
599 class IPyAutocallChecker(PrefilterChecker):
600
600
601 priority = Int(300, config=True)
601 priority = Int(300, config=True)
602
602
603 def check(self, line_info):
603 def check(self, line_info):
604 "Instances of IPyAutocall in user_ns get autocalled immediately"
604 "Instances of IPyAutocall in user_ns get autocalled immediately"
605 obj = self.shell.user_ns.get(line_info.ifun, None)
605 obj = self.shell.user_ns.get(line_info.ifun, None)
606 if isinstance(obj, IPyAutocall):
606 if isinstance(obj, IPyAutocall):
607 obj.set_ip(self.shell)
607 obj.set_ip(self.shell)
608 return self.prefilter_manager.get_handler_by_name('auto')
608 return self.prefilter_manager.get_handler_by_name('auto')
609 else:
609 else:
610 return None
610 return None
611
611
612
612
613 class MultiLineMagicChecker(PrefilterChecker):
613 class MultiLineMagicChecker(PrefilterChecker):
614
614
615 priority = Int(400, config=True)
615 priority = Int(400, config=True)
616
616
617 def check(self, line_info):
617 def check(self, line_info):
618 "Allow ! and !! in multi-line statements if multi_line_specials is on"
618 "Allow ! and !! in multi-line statements if multi_line_specials is on"
619 # Note that this one of the only places we check the first character of
619 # Note that this one of the only places we check the first character of
620 # ifun and *not* the pre_char. Also note that the below test matches
620 # ifun and *not* the pre_char. Also note that the below test matches
621 # both ! and !!.
621 # both ! and !!.
622 if line_info.continue_prompt \
622 if line_info.continue_prompt \
623 and self.prefilter_manager.multi_line_specials:
623 and self.prefilter_manager.multi_line_specials:
624 if line_info.ifun.startswith(ESC_MAGIC):
624 if line_info.ifun.startswith(ESC_MAGIC):
625 return self.prefilter_manager.get_handler_by_name('magic')
625 return self.prefilter_manager.get_handler_by_name('magic')
626 else:
626 else:
627 return None
627 return None
628
628
629
629
630 class EscCharsChecker(PrefilterChecker):
630 class EscCharsChecker(PrefilterChecker):
631
631
632 priority = Int(500, config=True)
632 priority = Int(500, config=True)
633
633
634 def check(self, line_info):
634 def check(self, line_info):
635 """Check for escape character and return either a handler to handle it,
635 """Check for escape character and return either a handler to handle it,
636 or None if there is no escape char."""
636 or None if there is no escape char."""
637 if line_info.line[-1] == ESC_HELP \
637 if line_info.line[-1] == ESC_HELP \
638 and line_info.pre_char != ESC_SHELL \
638 and line_info.pre_char != ESC_SHELL \
639 and line_info.pre_char != ESC_SH_CAP:
639 and line_info.pre_char != ESC_SH_CAP:
640 # the ? can be at the end, but *not* for either kind of shell escape,
640 # the ? can be at the end, but *not* for either kind of shell escape,
641 # because a ? can be a vaild final char in a shell cmd
641 # because a ? can be a vaild final char in a shell cmd
642 return self.prefilter_manager.get_handler_by_name('help')
642 return self.prefilter_manager.get_handler_by_name('help')
643 else:
643 else:
644 # This returns None like it should if no handler exists
644 # This returns None like it should if no handler exists
645 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
645 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
646
646
647
647
648 class AssignmentChecker(PrefilterChecker):
648 class AssignmentChecker(PrefilterChecker):
649
649
650 priority = Int(600, config=True)
650 priority = Int(600, config=True)
651
651
652 def check(self, line_info):
652 def check(self, line_info):
653 """Check to see if user is assigning to a var for the first time, in
653 """Check to see if user is assigning to a var for the first time, in
654 which case we want to avoid any sort of automagic / autocall games.
654 which case we want to avoid any sort of automagic / autocall games.
655
655
656 This allows users to assign to either alias or magic names true python
656 This allows users to assign to either alias or magic names true python
657 variables (the magic/alias systems always take second seat to true
657 variables (the magic/alias systems always take second seat to true
658 python code). E.g. ls='hi', or ls,that=1,2"""
658 python code). E.g. ls='hi', or ls,that=1,2"""
659 if line_info.the_rest:
659 if line_info.the_rest:
660 if line_info.the_rest[0] in '=,':
660 if line_info.the_rest[0] in '=,':
661 return self.prefilter_manager.get_handler_by_name('normal')
661 return self.prefilter_manager.get_handler_by_name('normal')
662 else:
662 else:
663 return None
663 return None
664
664
665
665
666 class AutoMagicChecker(PrefilterChecker):
666 class AutoMagicChecker(PrefilterChecker):
667
667
668 priority = Int(700, config=True)
668 priority = Int(700, config=True)
669
669
670 def check(self, line_info):
670 def check(self, line_info):
671 """If the ifun is magic, and automagic is on, run it. Note: normal,
671 """If the ifun is magic, and automagic is on, run it. Note: normal,
672 non-auto magic would already have been triggered via '%' in
672 non-auto magic would already have been triggered via '%' in
673 check_esc_chars. This just checks for automagic. Also, before
673 check_esc_chars. This just checks for automagic. Also, before
674 triggering the magic handler, make sure that there is nothing in the
674 triggering the magic handler, make sure that there is nothing in the
675 user namespace which could shadow it."""
675 user namespace which could shadow it."""
676 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
676 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
677 return None
677 return None
678
678
679 # We have a likely magic method. Make sure we should actually call it.
679 # We have a likely magic method. Make sure we should actually call it.
680 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
680 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
681 return None
681 return None
682
682
683 head = line_info.ifun.split('.',1)[0]
683 head = line_info.ifun.split('.',1)[0]
684 if is_shadowed(head, self.shell):
684 if is_shadowed(head, self.shell):
685 return None
685 return None
686
686
687 return self.prefilter_manager.get_handler_by_name('magic')
687 return self.prefilter_manager.get_handler_by_name('magic')
688
688
689
689
690 class AliasChecker(PrefilterChecker):
690 class AliasChecker(PrefilterChecker):
691
691
692 priority = Int(800, config=True)
692 priority = Int(800, config=True)
693
693
694 def check(self, line_info):
694 def check(self, line_info):
695 "Check if the initital identifier on the line is an alias."
695 "Check if the initital identifier on the line is an alias."
696 # Note: aliases can not contain '.'
696 # Note: aliases can not contain '.'
697 head = line_info.ifun.split('.',1)[0]
697 head = line_info.ifun.split('.',1)[0]
698 if line_info.ifun not in self.shell.alias_manager \
698 if line_info.ifun not in self.shell.alias_manager \
699 or head not in self.shell.alias_manager \
699 or head not in self.shell.alias_manager \
700 or is_shadowed(head, self.shell):
700 or is_shadowed(head, self.shell):
701 return None
701 return None
702
702
703 return self.prefilter_manager.get_handler_by_name('alias')
703 return self.prefilter_manager.get_handler_by_name('alias')
704
704
705
705
706 class PythonOpsChecker(PrefilterChecker):
706 class PythonOpsChecker(PrefilterChecker):
707
707
708 priority = Int(900, config=True)
708 priority = Int(900, config=True)
709
709
710 def check(self, line_info):
710 def check(self, line_info):
711 """If the 'rest' of the line begins with a function call or pretty much
711 """If the 'rest' of the line begins with a function call or pretty much
712 any python operator, we should simply execute the line (regardless of
712 any python operator, we should simply execute the line (regardless of
713 whether or not there's a possible autocall expansion). This avoids
713 whether or not there's a possible autocall expansion). This avoids
714 spurious (and very confusing) geattr() accesses."""
714 spurious (and very confusing) geattr() accesses."""
715 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
715 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
716 return self.prefilter_manager.get_handler_by_name('normal')
716 return self.prefilter_manager.get_handler_by_name('normal')
717 else:
717 else:
718 return None
718 return None
719
719
720
720
721 class AutocallChecker(PrefilterChecker):
721 class AutocallChecker(PrefilterChecker):
722
722
723 priority = Int(1000, config=True)
723 priority = Int(1000, config=True)
724
724
725 def check(self, line_info):
725 def check(self, line_info):
726 "Check if the initial word/function is callable and autocall is on."
726 "Check if the initial word/function is callable and autocall is on."
727 if not self.shell.autocall:
727 if not self.shell.autocall:
728 return None
728 return None
729
729
730 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
730 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
731 if not oinfo['found']:
731 if not oinfo['found']:
732 return None
732 return None
733
733
734 if callable(oinfo['obj']) \
734 if callable(oinfo['obj']) \
735 and (not re_exclude_auto.match(line_info.the_rest)) \
735 and (not re_exclude_auto.match(line_info.the_rest)) \
736 and re_fun_name.match(line_info.ifun):
736 and re_fun_name.match(line_info.ifun):
737 return self.prefilter_manager.get_handler_by_name('auto')
737 return self.prefilter_manager.get_handler_by_name('auto')
738 else:
738 else:
739 return None
739 return None
740
740
741
741
742 #-----------------------------------------------------------------------------
742 #-----------------------------------------------------------------------------
743 # Prefilter handlers
743 # Prefilter handlers
744 #-----------------------------------------------------------------------------
744 #-----------------------------------------------------------------------------
745
745
746
746
747 class PrefilterHandler(Configurable):
747 class PrefilterHandler(Configurable):
748
748
749 handler_name = Str('normal')
749 handler_name = Str('normal')
750 esc_strings = List([])
750 esc_strings = List([])
751 shell = Instance('IPython.core.iplib.InteractiveShell')
751 shell = Instance('IPython.core.iplib.InteractiveShellABC')
752 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
752 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
753
753
754 def __init__(self, shell, prefilter_manager, config=None):
754 def __init__(self, shell, prefilter_manager, config=None):
755 super(PrefilterHandler, self).__init__(config=config)
755 super(PrefilterHandler, self).__init__(config=config)
756 self.shell = shell
756 self.shell = shell
757 self.prefilter_manager = prefilter_manager
757 self.prefilter_manager = prefilter_manager
758 self.prefilter_manager.register_handler(
758 self.prefilter_manager.register_handler(
759 self.handler_name,
759 self.handler_name,
760 self,
760 self,
761 self.esc_strings
761 self.esc_strings
762 )
762 )
763
763
764 def handle(self, line_info):
764 def handle(self, line_info):
765 # print "normal: ", line_info
765 # print "normal: ", line_info
766 """Handle normal input lines. Use as a template for handlers."""
766 """Handle normal input lines. Use as a template for handlers."""
767
767
768 # With autoindent on, we need some way to exit the input loop, and I
768 # With autoindent on, we need some way to exit the input loop, and I
769 # don't want to force the user to have to backspace all the way to
769 # don't want to force the user to have to backspace all the way to
770 # clear the line. The rule will be in this case, that either two
770 # clear the line. The rule will be in this case, that either two
771 # lines of pure whitespace in a row, or a line of pure whitespace but
771 # lines of pure whitespace in a row, or a line of pure whitespace but
772 # of a size different to the indent level, will exit the input loop.
772 # of a size different to the indent level, will exit the input loop.
773 line = line_info.line
773 line = line_info.line
774 continue_prompt = line_info.continue_prompt
774 continue_prompt = line_info.continue_prompt
775
775
776 if (continue_prompt and
776 if (continue_prompt and
777 self.shell.autoindent and
777 self.shell.autoindent and
778 line.isspace() and
778 line.isspace() and
779
779
780 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
780 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
781 or
781 or
782 not self.shell.buffer
782 not self.shell.buffer
783 or
783 or
784 (self.shell.buffer[-1]).isspace()
784 (self.shell.buffer[-1]).isspace()
785 )
785 )
786 ):
786 ):
787 line = ''
787 line = ''
788
788
789 self.shell.log(line, line, continue_prompt)
789 self.shell.log(line, line, continue_prompt)
790 return line
790 return line
791
791
792 def __str__(self):
792 def __str__(self):
793 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
793 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
794
794
795
795
796 class AliasHandler(PrefilterHandler):
796 class AliasHandler(PrefilterHandler):
797
797
798 handler_name = Str('alias')
798 handler_name = Str('alias')
799
799
800 def handle(self, line_info):
800 def handle(self, line_info):
801 """Handle alias input lines. """
801 """Handle alias input lines. """
802 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
802 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
803 # pre is needed, because it carries the leading whitespace. Otherwise
803 # pre is needed, because it carries the leading whitespace. Otherwise
804 # aliases won't work in indented sections.
804 # aliases won't work in indented sections.
805 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
805 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
806 make_quoted_expr(transformed))
806 make_quoted_expr(transformed))
807
807
808 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
808 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
809 return line_out
809 return line_out
810
810
811
811
812 class ShellEscapeHandler(PrefilterHandler):
812 class ShellEscapeHandler(PrefilterHandler):
813
813
814 handler_name = Str('shell')
814 handler_name = Str('shell')
815 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
815 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
816
816
817 def handle(self, line_info):
817 def handle(self, line_info):
818 """Execute the line in a shell, empty return value"""
818 """Execute the line in a shell, empty return value"""
819 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
819 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
820
820
821 line = line_info.line
821 line = line_info.line
822 if line.lstrip().startswith(ESC_SH_CAP):
822 if line.lstrip().startswith(ESC_SH_CAP):
823 # rewrite LineInfo's line, ifun and the_rest to properly hold the
823 # rewrite LineInfo's line, ifun and the_rest to properly hold the
824 # call to %sx and the actual command to be executed, so
824 # call to %sx and the actual command to be executed, so
825 # handle_magic can work correctly. Note that this works even if
825 # handle_magic can work correctly. Note that this works even if
826 # the line is indented, so it handles multi_line_specials
826 # the line is indented, so it handles multi_line_specials
827 # properly.
827 # properly.
828 new_rest = line.lstrip()[2:]
828 new_rest = line.lstrip()[2:]
829 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
829 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
830 line_info.ifun = 'sx'
830 line_info.ifun = 'sx'
831 line_info.the_rest = new_rest
831 line_info.the_rest = new_rest
832 return magic_handler.handle(line_info)
832 return magic_handler.handle(line_info)
833 else:
833 else:
834 cmd = line.lstrip().lstrip(ESC_SHELL)
834 cmd = line.lstrip().lstrip(ESC_SHELL)
835 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
835 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
836 make_quoted_expr(cmd))
836 make_quoted_expr(cmd))
837 # update cache/log and return
837 # update cache/log and return
838 self.shell.log(line, line_out, line_info.continue_prompt)
838 self.shell.log(line, line_out, line_info.continue_prompt)
839 return line_out
839 return line_out
840
840
841
841
842 class MagicHandler(PrefilterHandler):
842 class MagicHandler(PrefilterHandler):
843
843
844 handler_name = Str('magic')
844 handler_name = Str('magic')
845 esc_strings = List([ESC_MAGIC])
845 esc_strings = List([ESC_MAGIC])
846
846
847 def handle(self, line_info):
847 def handle(self, line_info):
848 """Execute magic functions."""
848 """Execute magic functions."""
849 ifun = line_info.ifun
849 ifun = line_info.ifun
850 the_rest = line_info.the_rest
850 the_rest = line_info.the_rest
851 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
851 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
852 make_quoted_expr(ifun + " " + the_rest))
852 make_quoted_expr(ifun + " " + the_rest))
853 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
853 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
854 return cmd
854 return cmd
855
855
856
856
857 class AutoHandler(PrefilterHandler):
857 class AutoHandler(PrefilterHandler):
858
858
859 handler_name = Str('auto')
859 handler_name = Str('auto')
860 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
860 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
861
861
862 def handle(self, line_info):
862 def handle(self, line_info):
863 """Handle lines which can be auto-executed, quoting if requested."""
863 """Handle lines which can be auto-executed, quoting if requested."""
864 line = line_info.line
864 line = line_info.line
865 ifun = line_info.ifun
865 ifun = line_info.ifun
866 the_rest = line_info.the_rest
866 the_rest = line_info.the_rest
867 pre = line_info.pre
867 pre = line_info.pre
868 continue_prompt = line_info.continue_prompt
868 continue_prompt = line_info.continue_prompt
869 obj = line_info.ofind(self)['obj']
869 obj = line_info.ofind(self)['obj']
870 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
870 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
871
871
872 # This should only be active for single-line input!
872 # This should only be active for single-line input!
873 if continue_prompt:
873 if continue_prompt:
874 self.shell.log(line,line,continue_prompt)
874 self.shell.log(line,line,continue_prompt)
875 return line
875 return line
876
876
877 force_auto = isinstance(obj, IPyAutocall)
877 force_auto = isinstance(obj, IPyAutocall)
878 auto_rewrite = True
878 auto_rewrite = True
879
879
880 if pre == ESC_QUOTE:
880 if pre == ESC_QUOTE:
881 # Auto-quote splitting on whitespace
881 # Auto-quote splitting on whitespace
882 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
882 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
883 elif pre == ESC_QUOTE2:
883 elif pre == ESC_QUOTE2:
884 # Auto-quote whole string
884 # Auto-quote whole string
885 newcmd = '%s("%s")' % (ifun,the_rest)
885 newcmd = '%s("%s")' % (ifun,the_rest)
886 elif pre == ESC_PAREN:
886 elif pre == ESC_PAREN:
887 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
887 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
888 else:
888 else:
889 # Auto-paren.
889 # Auto-paren.
890 # We only apply it to argument-less calls if the autocall
890 # We only apply it to argument-less calls if the autocall
891 # parameter is set to 2. We only need to check that autocall is <
891 # parameter is set to 2. We only need to check that autocall is <
892 # 2, since this function isn't called unless it's at least 1.
892 # 2, since this function isn't called unless it's at least 1.
893 if not the_rest and (self.shell.autocall < 2) and not force_auto:
893 if not the_rest and (self.shell.autocall < 2) and not force_auto:
894 newcmd = '%s %s' % (ifun,the_rest)
894 newcmd = '%s %s' % (ifun,the_rest)
895 auto_rewrite = False
895 auto_rewrite = False
896 else:
896 else:
897 if not force_auto and the_rest.startswith('['):
897 if not force_auto and the_rest.startswith('['):
898 if hasattr(obj,'__getitem__'):
898 if hasattr(obj,'__getitem__'):
899 # Don't autocall in this case: item access for an object
899 # Don't autocall in this case: item access for an object
900 # which is BOTH callable and implements __getitem__.
900 # which is BOTH callable and implements __getitem__.
901 newcmd = '%s %s' % (ifun,the_rest)
901 newcmd = '%s %s' % (ifun,the_rest)
902 auto_rewrite = False
902 auto_rewrite = False
903 else:
903 else:
904 # if the object doesn't support [] access, go ahead and
904 # if the object doesn't support [] access, go ahead and
905 # autocall
905 # autocall
906 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
906 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
907 elif the_rest.endswith(';'):
907 elif the_rest.endswith(';'):
908 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
908 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
909 else:
909 else:
910 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
910 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
911
911
912 if auto_rewrite:
912 if auto_rewrite:
913 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
913 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
914
914
915 try:
915 try:
916 # plain ascii works better w/ pyreadline, on some machines, so
916 # plain ascii works better w/ pyreadline, on some machines, so
917 # we use it and only print uncolored rewrite if we have unicode
917 # we use it and only print uncolored rewrite if we have unicode
918 rw = str(rw)
918 rw = str(rw)
919 print >>Term.cout, rw
919 print >>Term.cout, rw
920 except UnicodeEncodeError:
920 except UnicodeEncodeError:
921 print "-------------->" + newcmd
921 print "-------------->" + newcmd
922
922
923 # log what is now valid Python, not the actual user input (without the
923 # log what is now valid Python, not the actual user input (without the
924 # final newline)
924 # final newline)
925 self.shell.log(line,newcmd,continue_prompt)
925 self.shell.log(line,newcmd,continue_prompt)
926 return newcmd
926 return newcmd
927
927
928
928
929 class HelpHandler(PrefilterHandler):
929 class HelpHandler(PrefilterHandler):
930
930
931 handler_name = Str('help')
931 handler_name = Str('help')
932 esc_strings = List([ESC_HELP])
932 esc_strings = List([ESC_HELP])
933
933
934 def handle(self, line_info):
934 def handle(self, line_info):
935 """Try to get some help for the object.
935 """Try to get some help for the object.
936
936
937 obj? or ?obj -> basic information.
937 obj? or ?obj -> basic information.
938 obj?? or ??obj -> more details.
938 obj?? or ??obj -> more details.
939 """
939 """
940 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
940 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
941 line = line_info.line
941 line = line_info.line
942 # We need to make sure that we don't process lines which would be
942 # We need to make sure that we don't process lines which would be
943 # otherwise valid python, such as "x=1 # what?"
943 # otherwise valid python, such as "x=1 # what?"
944 try:
944 try:
945 codeop.compile_command(line)
945 codeop.compile_command(line)
946 except SyntaxError:
946 except SyntaxError:
947 # We should only handle as help stuff which is NOT valid syntax
947 # We should only handle as help stuff which is NOT valid syntax
948 if line[0]==ESC_HELP:
948 if line[0]==ESC_HELP:
949 line = line[1:]
949 line = line[1:]
950 elif line[-1]==ESC_HELP:
950 elif line[-1]==ESC_HELP:
951 line = line[:-1]
951 line = line[:-1]
952 self.shell.log(line, '#?'+line, line_info.continue_prompt)
952 self.shell.log(line, '#?'+line, line_info.continue_prompt)
953 if line:
953 if line:
954 #print 'line:<%r>' % line # dbg
954 #print 'line:<%r>' % line # dbg
955 self.shell.magic_pinfo(line)
955 self.shell.magic_pinfo(line)
956 else:
956 else:
957 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
957 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
958 return '' # Empty string is needed here!
958 return '' # Empty string is needed here!
959 except:
959 except:
960 raise
960 raise
961 # Pass any other exceptions through to the normal handler
961 # Pass any other exceptions through to the normal handler
962 return normal_handler.handle(line_info)
962 return normal_handler.handle(line_info)
963 else:
963 else:
964 # If the code compiles ok, we should handle it normally
964 # If the code compiles ok, we should handle it normally
965 return normal_handler.handle(line_info)
965 return normal_handler.handle(line_info)
966
966
967
967
968 class EmacsHandler(PrefilterHandler):
968 class EmacsHandler(PrefilterHandler):
969
969
970 handler_name = Str('emacs')
970 handler_name = Str('emacs')
971 esc_strings = List([])
971 esc_strings = List([])
972
972
973 def handle(self, line_info):
973 def handle(self, line_info):
974 """Handle input lines marked by python-mode."""
974 """Handle input lines marked by python-mode."""
975
975
976 # Currently, nothing is done. Later more functionality can be added
976 # Currently, nothing is done. Later more functionality can be added
977 # here if needed.
977 # here if needed.
978
978
979 # The input cache shouldn't be updated
979 # The input cache shouldn't be updated
980 return line_info.line
980 return line_info.line
981
981
982
982
983 #-----------------------------------------------------------------------------
983 #-----------------------------------------------------------------------------
984 # Defaults
984 # Defaults
985 #-----------------------------------------------------------------------------
985 #-----------------------------------------------------------------------------
986
986
987
987
988 _default_transformers = [
988 _default_transformers = [
989 AssignSystemTransformer,
989 AssignSystemTransformer,
990 AssignMagicTransformer,
990 AssignMagicTransformer,
991 PyPromptTransformer,
991 PyPromptTransformer,
992 IPyPromptTransformer,
992 IPyPromptTransformer,
993 ]
993 ]
994
994
995 _default_checkers = [
995 _default_checkers = [
996 EmacsChecker,
996 EmacsChecker,
997 ShellEscapeChecker,
997 ShellEscapeChecker,
998 IPyAutocallChecker,
998 IPyAutocallChecker,
999 MultiLineMagicChecker,
999 MultiLineMagicChecker,
1000 EscCharsChecker,
1000 EscCharsChecker,
1001 AssignmentChecker,
1001 AssignmentChecker,
1002 AutoMagicChecker,
1002 AutoMagicChecker,
1003 AliasChecker,
1003 AliasChecker,
1004 PythonOpsChecker,
1004 PythonOpsChecker,
1005 AutocallChecker
1005 AutocallChecker
1006 ]
1006 ]
1007
1007
1008 _default_handlers = [
1008 _default_handlers = [
1009 PrefilterHandler,
1009 PrefilterHandler,
1010 AliasHandler,
1010 AliasHandler,
1011 ShellEscapeHandler,
1011 ShellEscapeHandler,
1012 MagicHandler,
1012 MagicHandler,
1013 AutoHandler,
1013 AutoHandler,
1014 HelpHandler,
1014 HelpHandler,
1015 EmacsHandler
1015 EmacsHandler
1016 ]
1016 ]
@@ -1,201 +1,202 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Magic command interface for interactive parallel work."""
4 """Magic command interface for interactive parallel work."""
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import new
17 import new
18
18
19 from IPython.config.configurable import Configurable
19 from IPython.core.plugin import Plugin
20 from IPython.utils.traitlets import Bool, Any, Instance
20 from IPython.utils.traitlets import Bool, Any, Instance
21 from IPython.utils.autoattr import auto_attr
21 from IPython.utils.autoattr import auto_attr
22 from IPython.testing import decorators as testdec
22 from IPython.testing import decorators as testdec
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Definitions of magic functions for use with IPython
25 # Definitions of magic functions for use with IPython
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 NO_ACTIVE_MULTIENGINE_CLIENT = """
29 NO_ACTIVE_MULTIENGINE_CLIENT = """
30 Use activate() on a MultiEngineClient object to activate it for magics.
30 Use activate() on a MultiEngineClient object to activate it for magics.
31 """
31 """
32
32
33
33
34 class ParalleMagicComponent(Configurable):
34 class ParalleMagic(Plugin):
35 """A component to manage the %result, %px and %autopx magics."""
35 """A component to manage the %result, %px and %autopx magics."""
36
36
37 active_multiengine_client = Any()
37 active_multiengine_client = Any()
38 verbose = Bool(False, config=True)
38 verbose = Bool(False, config=True)
39 shell = Instance('IPython.core.iplib.InteractiveShell')
39 shell = Instance('IPython.core.iplib.InteractiveShellABC')
40
40
41 def __init__(self, shell, config=None):
41 def __init__(self, shell, config=None):
42 super(ParalleMagicComponent, self).__init__(config=config)
42 super(ParalleMagic, self).__init__(config=config)
43 self.shell = shell
43 self.shell = shell
44 self._define_magics()
44 self._define_magics()
45 # A flag showing if autopx is activated or not
45 # A flag showing if autopx is activated or not
46 self.autopx = False
46 self.autopx = False
47
47
48 def _define_magics(self):
48 def _define_magics(self):
49 """Define the magic functions."""
49 """Define the magic functions."""
50 self.shell.define_magic('result', self.magic_result)
50 self.shell.define_magic('result', self.magic_result)
51 self.shell.define_magic('px', self.magic_px)
51 self.shell.define_magic('px', self.magic_px)
52 self.shell.define_magic('autopx', self.magic_autopx)
52 self.shell.define_magic('autopx', self.magic_autopx)
53
53
54 @testdec.skip_doctest
54 @testdec.skip_doctest
55 def magic_result(self, ipself, parameter_s=''):
55 def magic_result(self, ipself, parameter_s=''):
56 """Print the result of command i on all engines..
56 """Print the result of command i on all engines..
57
57
58 To use this a :class:`MultiEngineClient` instance must be created
58 To use this a :class:`MultiEngineClient` instance must be created
59 and then activated by calling its :meth:`activate` method.
59 and then activated by calling its :meth:`activate` method.
60
60
61 Then you can do the following::
61 Then you can do the following::
62
62
63 In [23]: %result
63 In [23]: %result
64 Out[23]:
64 Out[23]:
65 <Results List>
65 <Results List>
66 [0] In [6]: a = 10
66 [0] In [6]: a = 10
67 [1] In [6]: a = 10
67 [1] In [6]: a = 10
68
68
69 In [22]: %result 6
69 In [22]: %result 6
70 Out[22]:
70 Out[22]:
71 <Results List>
71 <Results List>
72 [0] In [6]: a = 10
72 [0] In [6]: a = 10
73 [1] In [6]: a = 10
73 [1] In [6]: a = 10
74 """
74 """
75 if self.active_multiengine_client is None:
75 if self.active_multiengine_client is None:
76 print NO_ACTIVE_MULTIENGINE_CLIENT
76 print NO_ACTIVE_MULTIENGINE_CLIENT
77 return
77 return
78
78
79 try:
79 try:
80 index = int(parameter_s)
80 index = int(parameter_s)
81 except:
81 except:
82 index = None
82 index = None
83 result = self.active_multiengine_client.get_result(index)
83 result = self.active_multiengine_client.get_result(index)
84 return result
84 return result
85
85
86 @testdec.skip_doctest
86 @testdec.skip_doctest
87 def magic_px(self, ipself, parameter_s=''):
87 def magic_px(self, ipself, parameter_s=''):
88 """Executes the given python command in parallel.
88 """Executes the given python command in parallel.
89
89
90 To use this a :class:`MultiEngineClient` instance must be created
90 To use this a :class:`MultiEngineClient` instance must be created
91 and then activated by calling its :meth:`activate` method.
91 and then activated by calling its :meth:`activate` method.
92
92
93 Then you can do the following::
93 Then you can do the following::
94
94
95 In [24]: %px a = 5
95 In [24]: %px a = 5
96 Parallel execution on engines: all
96 Parallel execution on engines: all
97 Out[24]:
97 Out[24]:
98 <Results List>
98 <Results List>
99 [0] In [7]: a = 5
99 [0] In [7]: a = 5
100 [1] In [7]: a = 5
100 [1] In [7]: a = 5
101 """
101 """
102
102
103 if self.active_multiengine_client is None:
103 if self.active_multiengine_client is None:
104 print NO_ACTIVE_MULTIENGINE_CLIENT
104 print NO_ACTIVE_MULTIENGINE_CLIENT
105 return
105 return
106 print "Parallel execution on engines: %s" % self.active_multiengine_client.targets
106 print "Parallel execution on engines: %s" % self.active_multiengine_client.targets
107 result = self.active_multiengine_client.execute(parameter_s)
107 result = self.active_multiengine_client.execute(parameter_s)
108 return result
108 return result
109
109
110 @testdec.skip_doctest
110 @testdec.skip_doctest
111 def magic_autopx(self, ipself, parameter_s=''):
111 def magic_autopx(self, ipself, parameter_s=''):
112 """Toggles auto parallel mode.
112 """Toggles auto parallel mode.
113
113
114 To use this a :class:`MultiEngineClient` instance must be created
114 To use this a :class:`MultiEngineClient` instance must be created
115 and then activated by calling its :meth:`activate` method. Once this
115 and then activated by calling its :meth:`activate` method. Once this
116 is called, all commands typed at the command line are send to
116 is called, all commands typed at the command line are send to
117 the engines to be executed in parallel. To control which engine
117 the engines to be executed in parallel. To control which engine
118 are used, set the ``targets`` attributed of the multiengine client
118 are used, set the ``targets`` attributed of the multiengine client
119 before entering ``%autopx`` mode.
119 before entering ``%autopx`` mode.
120
120
121 Then you can do the following::
121 Then you can do the following::
122
122
123 In [25]: %autopx
123 In [25]: %autopx
124 %autopx to enabled
124 %autopx to enabled
125
125
126 In [26]: a = 10
126 In [26]: a = 10
127 <Results List>
127 <Results List>
128 [0] In [8]: a = 10
128 [0] In [8]: a = 10
129 [1] In [8]: a = 10
129 [1] In [8]: a = 10
130
130
131
131
132 In [27]: %autopx
132 In [27]: %autopx
133 %autopx disabled
133 %autopx disabled
134 """
134 """
135 if self.autopx:
135 if self.autopx:
136 self._disable_autopx()
136 self._disable_autopx()
137 else:
137 else:
138 self._enable_autopx()
138 self._enable_autopx()
139
139
140 def _enable_autopx(self):
140 def _enable_autopx(self):
141 """Enable %autopx mode by saving the original runsource and installing
141 """Enable %autopx mode by saving the original runsource and installing
142 pxrunsource.
142 pxrunsource.
143 """
143 """
144 if self.active_multiengine_client is None:
144 if self.active_multiengine_client is None:
145 print NO_ACTIVE_MULTIENGINE_CLIENT
145 print NO_ACTIVE_MULTIENGINE_CLIENT
146 return
146 return
147
147
148 self._original_runsource = self.shell.runsource
148 self._original_runsource = self.shell.runsource
149 self.shell.runsource = new.instancemethod(
149 self.shell.runsource = new.instancemethod(
150 self.pxrunsource, self.shell, self.shell.__class__
150 self.pxrunsource, self.shell, self.shell.__class__
151 )
151 )
152 self.autopx = True
152 self.autopx = True
153 print "%autopx enabled"
153 print "%autopx enabled"
154
154
155 def _disable_autopx(self):
155 def _disable_autopx(self):
156 """Disable %autopx by restoring the original InteractiveShell.runsource."""
156 """Disable %autopx by restoring the original InteractiveShell.runsource."""
157 if self.autopx:
157 if self.autopx:
158 self.shell.runsource = self._original_runsource
158 self.shell.runsource = self._original_runsource
159 self.autopx = False
159 self.autopx = False
160 print "%autopx disabled"
160 print "%autopx disabled"
161
161
162 def pxrunsource(self, ipself, source, filename="<input>", symbol="single"):
162 def pxrunsource(self, ipself, source, filename="<input>", symbol="single"):
163 """A parallel replacement for InteractiveShell.runsource."""
163 """A parallel replacement for InteractiveShell.runsource."""
164
164
165 try:
165 try:
166 code = ipself.compile(source, filename, symbol)
166 code = ipself.compile(source, filename, symbol)
167 except (OverflowError, SyntaxError, ValueError):
167 except (OverflowError, SyntaxError, ValueError):
168 # Case 1
168 # Case 1
169 ipself.showsyntaxerror(filename)
169 ipself.showsyntaxerror(filename)
170 return None
170 return None
171
171
172 if code is None:
172 if code is None:
173 # Case 2
173 # Case 2
174 return True
174 return True
175
175
176 # Case 3
176 # Case 3
177 # Because autopx is enabled, we now call executeAll or disable autopx if
177 # Because autopx is enabled, we now call executeAll or disable autopx if
178 # %autopx or autopx has been called
178 # %autopx or autopx has been called
179 if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source:
179 if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source:
180 self._disable_autopx()
180 self._disable_autopx()
181 return False
181 return False
182 else:
182 else:
183 try:
183 try:
184 result = self.active_multiengine_client.execute(source)
184 result = self.active_multiengine_client.execute(source)
185 except:
185 except:
186 ipself.showtraceback()
186 ipself.showtraceback()
187 else:
187 else:
188 print result.__repr__()
188 print result.__repr__()
189 return False
189 return False
190
190
191
191
192 _loaded = False
192 _loaded = False
193
193
194
194
195 def load_ipython_extension(ip):
195 def load_ipython_extension(ip):
196 """Load the extension in IPython."""
196 """Load the extension in IPython."""
197 global _loaded
197 global _loaded
198 if not _loaded:
198 if not _loaded:
199 prd = ParalleMagicComponent(ip, config=ip.config)
199 plugin = ParalleMagic(ip, config=ip.config)
200 ip.plugin_manager.register_plugin('parallel_magic', plugin)
200 _loaded = True
201 _loaded = True
201
202
@@ -1,158 +1,158 b''
1 """Use pretty.py for configurable pretty-printing.
1 """Use pretty.py for configurable pretty-printing.
2
2
3 To enable this extension in your configuration
3 To enable this extension in your configuration
4 file, add the following to :file:`ipython_config.py`::
4 file, add the following to :file:`ipython_config.py`::
5
5
6 c.Global.extensions = ['IPython.extensions.pretty']
6 c.Global.extensions = ['IPython.extensions.pretty']
7 def dict_pprinter(obj, p, cycle):
7 def dict_pprinter(obj, p, cycle):
8 return p.text("<dict>")
8 return p.text("<dict>")
9 c.PrettyResultDisplay.verbose = True
9 c.PrettyResultDisplay.verbose = True
10 c.PrettyResultDisplay.defaults_for_type = [
10 c.PrettyResultDisplay.defaults_for_type = [
11 (dict, dict_pprinter)
11 (dict, dict_pprinter)
12 ]
12 ]
13 c.PrettyResultDisplay.defaults_for_type_by_name = [
13 c.PrettyResultDisplay.defaults_for_type_by_name = [
14 ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
14 ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
15 ]
15 ]
16
16
17 This extension can also be loaded by using the ``%load_ext`` magic::
17 This extension can also be loaded by using the ``%load_ext`` magic::
18
18
19 %load_ext IPython.extensions.pretty
19 %load_ext IPython.extensions.pretty
20
20
21 If this extension is enabled, you can always add additional pretty printers
21 If this extension is enabled, you can always add additional pretty printers
22 by doing::
22 by doing::
23
23
24 ip = get_ipython()
24 ip = get_ipython()
25 prd = ip.get_component('pretty_result_display')
25 prd = ip.get_component('pretty_result_display')
26 import numpy
26 import numpy
27 from IPython.extensions.pretty import dtype_pprinter
27 from IPython.extensions.pretty import dtype_pprinter
28 prd.for_type(numpy.dtype, dtype_pprinter)
28 prd.for_type(numpy.dtype, dtype_pprinter)
29
29
30 # If you don't want to have numpy imported until it needs to be:
30 # If you don't want to have numpy imported until it needs to be:
31 prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
31 prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
32 """
32 """
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Imports
35 # Imports
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 from IPython.core.error import TryNext
38 from IPython.core.error import TryNext
39 from IPython.external import pretty
39 from IPython.external import pretty
40 from IPython.config.configurable import Configurable
40 from IPython.core.plugin import Plugin
41 from IPython.utils.traitlets import Bool, List, Instance
41 from IPython.utils.traitlets import Bool, List, Instance
42 from IPython.utils.io import Term
42 from IPython.utils.io import Term
43 from IPython.utils.autoattr import auto_attr
43 from IPython.utils.autoattr import auto_attr
44 from IPython.utils.importstring import import_item
44 from IPython.utils.importstring import import_item
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Code
47 # Code
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50
50
51 _loaded = False
51 _loaded = False
52
52
53
53
54 class PrettyResultDisplay(Configurable):
54 class PrettyResultDisplay(Plugin):
55 """A component for pretty printing on steroids."""
55 """A component for pretty printing on steroids."""
56
56
57 verbose = Bool(False, config=True)
57 verbose = Bool(False, config=True)
58 shell = Instance('IPython.core.iplib.InteractiveShell')
58 shell = Instance('IPython.core.iplib.InteractiveShellABC')
59
59
60 # A list of (type, func_name), like
60 # A list of (type, func_name), like
61 # [(dict, 'my_dict_printer')]
61 # [(dict, 'my_dict_printer')]
62 # The final argument can also be a callable
62 # The final argument can also be a callable
63 defaults_for_type = List(default_value=[], config=True)
63 defaults_for_type = List(default_value=[], config=True)
64
64
65 # A list of (module_name, type_name, func_name), like
65 # A list of (module_name, type_name, func_name), like
66 # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
66 # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
67 # The final argument can also be a callable
67 # The final argument can also be a callable
68 defaults_for_type_by_name = List(default_value=[], config=True)
68 defaults_for_type_by_name = List(default_value=[], config=True)
69
69
70 def __init__(self, shell, config=None):
70 def __init__(self, shell, config=None):
71 super(PrettyResultDisplay, self).__init__(config=config)
71 super(PrettyResultDisplay, self).__init__(config=config)
72 self.shell = shell
72 self.shell = shell
73 self._setup_defaults()
73 self._setup_defaults()
74
74
75 def _setup_defaults(self):
75 def _setup_defaults(self):
76 """Initialize the default pretty printers."""
76 """Initialize the default pretty printers."""
77 for typ, func_name in self.defaults_for_type:
77 for typ, func_name in self.defaults_for_type:
78 func = self._resolve_func_name(func_name)
78 func = self._resolve_func_name(func_name)
79 self.for_type(typ, func)
79 self.for_type(typ, func)
80 for type_module, type_name, func_name in self.defaults_for_type_by_name:
80 for type_module, type_name, func_name in self.defaults_for_type_by_name:
81 func = self._resolve_func_name(func_name)
81 func = self._resolve_func_name(func_name)
82 self.for_type_by_name(type_module, type_name, func)
82 self.for_type_by_name(type_module, type_name, func)
83
83
84 def _resolve_func_name(self, func_name):
84 def _resolve_func_name(self, func_name):
85 if callable(func_name):
85 if callable(func_name):
86 return func_name
86 return func_name
87 elif isinstance(func_name, basestring):
87 elif isinstance(func_name, basestring):
88 return import_item(func_name)
88 return import_item(func_name)
89 else:
89 else:
90 raise TypeError('func_name must be a str or callable, got: %r' % func_name)
90 raise TypeError('func_name must be a str or callable, got: %r' % func_name)
91
91
92 def __call__(self, otherself, arg):
92 def __call__(self, otherself, arg):
93 """Uber-pretty-printing display hook.
93 """Uber-pretty-printing display hook.
94
94
95 Called for displaying the result to the user.
95 Called for displaying the result to the user.
96 """
96 """
97
97
98 if self.shell.pprint:
98 if self.shell.pprint:
99 out = pretty.pretty(arg, verbose=self.verbose)
99 out = pretty.pretty(arg, verbose=self.verbose)
100 if '\n' in out:
100 if '\n' in out:
101 # So that multi-line strings line up with the left column of
101 # So that multi-line strings line up with the left column of
102 # the screen, instead of having the output prompt mess up
102 # the screen, instead of having the output prompt mess up
103 # their first line.
103 # their first line.
104 Term.cout.write('\n')
104 Term.cout.write('\n')
105 print >>Term.cout, out
105 print >>Term.cout, out
106 else:
106 else:
107 raise TryNext
107 raise TryNext
108
108
109 def for_type(self, typ, func):
109 def for_type(self, typ, func):
110 """Add a pretty printer for a type."""
110 """Add a pretty printer for a type."""
111 return pretty.for_type(typ, func)
111 return pretty.for_type(typ, func)
112
112
113 def for_type_by_name(self, type_module, type_name, func):
113 def for_type_by_name(self, type_module, type_name, func):
114 """Add a pretty printer for a type by its name and module name."""
114 """Add a pretty printer for a type by its name and module name."""
115 return pretty.for_type_by_name(type_module, type_name, func)
115 return pretty.for_type_by_name(type_module, type_name, func)
116
116
117
117
118 #-----------------------------------------------------------------------------
118 #-----------------------------------------------------------------------------
119 # Initialization code for the extension
119 # Initialization code for the extension
120 #-----------------------------------------------------------------------------
120 #-----------------------------------------------------------------------------
121
121
122
122
123 def load_ipython_extension(ip):
123 def load_ipython_extension(ip):
124 """Load the extension in IPython as a hook."""
124 """Load the extension in IPython as a hook."""
125 global _loaded
125 global _loaded
126 if not _loaded:
126 if not _loaded:
127 prd = PrettyResultDisplay(ip, config=ip.config)
127 plugin = PrettyResultDisplay(ip, config=ip.config)
128 ip.set_hook('result_display', prd, priority=99)
128 ip.set_hook('result_display', plugin, priority=99)
129 _loaded = True
129 _loaded = True
130 return prd
130 ip.plugin_manager.register_plugin('pretty_result_display', plugin)
131
131
132 def unload_ipython_extension(ip):
132 def unload_ipython_extension(ip):
133 """Unload the extension."""
133 """Unload the extension."""
134 # The hook system does not have a way to remove a hook so this is a pass
134 # The hook system does not have a way to remove a hook so this is a pass
135 pass
135 pass
136
136
137
137
138 #-----------------------------------------------------------------------------
138 #-----------------------------------------------------------------------------
139 # Example pretty printers
139 # Example pretty printers
140 #-----------------------------------------------------------------------------
140 #-----------------------------------------------------------------------------
141
141
142
142
143 def dtype_pprinter(obj, p, cycle):
143 def dtype_pprinter(obj, p, cycle):
144 """ A pretty-printer for numpy dtype objects.
144 """ A pretty-printer for numpy dtype objects.
145 """
145 """
146 if cycle:
146 if cycle:
147 return p.text('dtype(...)')
147 return p.text('dtype(...)')
148 if hasattr(obj, 'fields'):
148 if hasattr(obj, 'fields'):
149 if obj.fields is None:
149 if obj.fields is None:
150 p.text(repr(obj))
150 p.text(repr(obj))
151 else:
151 else:
152 p.begin_group(7, 'dtype([')
152 p.begin_group(7, 'dtype([')
153 for i, field in enumerate(obj.descr):
153 for i, field in enumerate(obj.descr):
154 if i > 0:
154 if i > 0:
155 p.text(',')
155 p.text(',')
156 p.breakable()
156 p.breakable()
157 p.pretty(field)
157 p.pretty(field)
158 p.end_group(7, '])')
158 p.end_group(7, '])')
@@ -1,101 +1,100 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Simple tests for :mod:`IPython.extensions.pretty`.
4 Simple tests for :mod:`IPython.extensions.pretty`.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from unittest import TestCase
18 from unittest import TestCase
19
19
20 from IPython.core.component import Component, masquerade_as
20 from IPython.config.configurable import Configurable
21 from IPython.core.iplib import InteractiveShell
21 from IPython.core.iplib import InteractiveShellABC
22 from IPython.extensions import pretty as pretty_ext
22 from IPython.extensions import pretty as pretty_ext
23 from IPython.external import pretty
23 from IPython.external import pretty
24 from IPython.testing import decorators as dec
24 from IPython.testing import decorators as dec
25 from IPython.testing import tools as tt
25 from IPython.testing import tools as tt
26 from IPython.utils.traitlets import Bool
26 from IPython.utils.traitlets import Bool
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Tests
29 # Tests
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 class InteractiveShellStub(Component):
32 class InteractiveShellStub(Configurable):
33 pprint = Bool(True)
33 pprint = Bool(True)
34
34
35 InteractiveShellABC.register(InteractiveShellStub)
36
35 class A(object):
37 class A(object):
36 pass
38 pass
37
39
38 def a_pprinter(o, p, c):
40 def a_pprinter(o, p, c):
39 return p.text("<A>")
41 return p.text("<A>")
40
42
41 class TestPrettyResultDisplay(TestCase):
43 class TestPrettyResultDisplay(TestCase):
42
44
43 def setUp(self):
45 def setUp(self):
44 self.ip = InteractiveShellStub(None)
46 self.ip = InteractiveShellStub()
45 # This allows our stub to be retrieved instead of the real
47 self.prd = pretty_ext.PrettyResultDisplay(self.ip, config=None)
46 # InteractiveShell
47 masquerade_as(self.ip, InteractiveShell)
48 self.prd = pretty_ext.PrettyResultDisplay(self.ip,
49 name='pretty_result_display')
50
48
51 def test_for_type(self):
49 def test_for_type(self):
52 self.prd.for_type(A, a_pprinter)
50 self.prd.for_type(A, a_pprinter)
53 a = A()
51 a = A()
54 result = pretty.pretty(a)
52 result = pretty.pretty(a)
55 self.assertEquals(result, "<A>")
53 self.assertEquals(result, "<A>")
56
54
57 ipy_src = """
55 ipy_src = """
58 class A(object):
56 class A(object):
59 def __repr__(self):
57 def __repr__(self):
60 return 'A()'
58 return 'A()'
61
59
62 class B(object):
60 class B(object):
63 def __repr__(self):
61 def __repr__(self):
64 return 'B()'
62 return 'B()'
65
63
66 a = A()
64 a = A()
67 b = B()
65 b = B()
68
66
69 def a_pretty_printer(obj, p, cycle):
67 def a_pretty_printer(obj, p, cycle):
70 p.text('<A>')
68 p.text('<A>')
71
69
72 def b_pretty_printer(obj, p, cycle):
70 def b_pretty_printer(obj, p, cycle):
73 p.text('<B>')
71 p.text('<B>')
74
72
75
73
76 a
74 a
77 b
75 b
78
76
79 ip = get_ipython()
77 ip = get_ipython()
80 prd = ip.extension_manager.load_extension('pretty')
78 ip.extension_manager.load_extension('pretty')
79 prd = ip.plugin_manager.get_plugin('pretty_result_display')
81 prd.for_type(A, a_pretty_printer)
80 prd.for_type(A, a_pretty_printer)
82 prd.for_type_by_name(B.__module__, B.__name__, b_pretty_printer)
81 prd.for_type_by_name(B.__module__, B.__name__, b_pretty_printer)
83
82
84 a
83 a
85 b
84 b
86 """
85 """
87 ipy_out = """
86 ipy_out = """
88 A()
87 A()
89 B()
88 B()
90 <A>
89 <A>
91 <B>
90 <B>
92 """
91 """
93
92
94 class TestPrettyInteractively(tt.TempFileMixin):
93 class TestPrettyInteractively(tt.TempFileMixin):
95
94
96 # XXX Unfortunately, ipexec_validate fails under win32. If someone helps
95 # XXX Unfortunately, ipexec_validate fails under win32. If someone helps
97 # us write a win32-compatible version, we can reactivate this test.
96 # us write a win32-compatible version, we can reactivate this test.
98 @dec.skip_win32
97 @dec.skip_win32
99 def test_printers(self):
98 def test_printers(self):
100 self.mktmp(ipy_src, '.ipy')
99 self.mktmp(ipy_src, '.ipy')
101 tt.ipexec_validate(self.fname, ipy_out)
100 tt.ipexec_validate(self.fname, ipy_out)
@@ -1,174 +1,174 b''
1 """Global IPython app to support test running.
1 """Global IPython app to support test running.
2
2
3 We must start our own ipython object and heavily muck with it so that all the
3 We must start our own ipython object and heavily muck with it so that all the
4 modifications IPython makes to system behavior don't send the doctest machinery
4 modifications IPython makes to system behavior don't send the doctest machinery
5 into a fit. This code should be considered a gross hack, but it gets the job
5 into a fit. This code should be considered a gross hack, but it gets the job
6 done.
6 done.
7 """
7 """
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
12 # Copyright (C) 2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23 import commands
23 import commands
24 import os
24 import os
25 import sys
25 import sys
26
26
27 from . import tools
27 from . import tools
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Functions
30 # Functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 # Hack to modify the %run command so we can sync the user's namespace with the
33 # Hack to modify the %run command so we can sync the user's namespace with the
34 # test globals. Once we move over to a clean magic system, this will be done
34 # test globals. Once we move over to a clean magic system, this will be done
35 # with much less ugliness.
35 # with much less ugliness.
36
36
37 class py_file_finder(object):
37 class py_file_finder(object):
38 def __init__(self,test_filename):
38 def __init__(self,test_filename):
39 self.test_filename = test_filename
39 self.test_filename = test_filename
40
40
41 def __call__(self,name):
41 def __call__(self,name):
42 from IPython.utils.path import get_py_filename
42 from IPython.utils.path import get_py_filename
43 try:
43 try:
44 return get_py_filename(name)
44 return get_py_filename(name)
45 except IOError:
45 except IOError:
46 test_dir = os.path.dirname(self.test_filename)
46 test_dir = os.path.dirname(self.test_filename)
47 new_path = os.path.join(test_dir,name)
47 new_path = os.path.join(test_dir,name)
48 return get_py_filename(new_path)
48 return get_py_filename(new_path)
49
49
50
50
51 def _run_ns_sync(self,arg_s,runner=None):
51 def _run_ns_sync(self,arg_s,runner=None):
52 """Modified version of %run that syncs testing namespaces.
52 """Modified version of %run that syncs testing namespaces.
53
53
54 This is strictly needed for running doctests that call %run.
54 This is strictly needed for running doctests that call %run.
55 """
55 """
56 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
56 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
57
57
58 _ip = get_ipython()
58 _ip = get_ipython()
59 finder = py_file_finder(arg_s)
59 finder = py_file_finder(arg_s)
60 out = _ip.magic_run_ori(arg_s,runner,finder)
60 out = _ip.magic_run_ori(arg_s,runner,finder)
61 return out
61 return out
62
62
63
63
64 class ipnsdict(dict):
64 class ipnsdict(dict):
65 """A special subclass of dict for use as an IPython namespace in doctests.
65 """A special subclass of dict for use as an IPython namespace in doctests.
66
66
67 This subclass adds a simple checkpointing capability so that when testing
67 This subclass adds a simple checkpointing capability so that when testing
68 machinery clears it (we use it as the test execution context), it doesn't
68 machinery clears it (we use it as the test execution context), it doesn't
69 get completely destroyed.
69 get completely destroyed.
70 """
70 """
71
71
72 def __init__(self,*a):
72 def __init__(self,*a):
73 dict.__init__(self,*a)
73 dict.__init__(self,*a)
74 self._savedict = {}
74 self._savedict = {}
75
75
76 def clear(self):
76 def clear(self):
77 dict.clear(self)
77 dict.clear(self)
78 self.update(self._savedict)
78 self.update(self._savedict)
79
79
80 def _checkpoint(self):
80 def _checkpoint(self):
81 self._savedict.clear()
81 self._savedict.clear()
82 self._savedict.update(self)
82 self._savedict.update(self)
83
83
84 def update(self,other):
84 def update(self,other):
85 self._checkpoint()
85 self._checkpoint()
86 dict.update(self,other)
86 dict.update(self,other)
87
87
88 # If '_' is in the namespace, python won't set it when executing code,
88 # If '_' is in the namespace, python won't set it when executing code,
89 # and we have examples that test it. So we ensure that the namespace
89 # and we have examples that test it. So we ensure that the namespace
90 # is always 'clean' of it before it's used for test code execution.
90 # is always 'clean' of it before it's used for test code execution.
91 self.pop('_',None)
91 self.pop('_',None)
92
92
93 # The builtins namespace must *always* be the real __builtin__ module,
93 # The builtins namespace must *always* be the real __builtin__ module,
94 # else weird stuff happens. The main ipython code does have provisions
94 # else weird stuff happens. The main ipython code does have provisions
95 # to ensure this after %run, but since in this class we do some
95 # to ensure this after %run, but since in this class we do some
96 # aggressive low-level cleaning of the execution namespace, we need to
96 # aggressive low-level cleaning of the execution namespace, we need to
97 # correct for that ourselves, to ensure consitency with the 'real'
97 # correct for that ourselves, to ensure consitency with the 'real'
98 # ipython.
98 # ipython.
99 self['__builtins__'] = __builtin__
99 self['__builtins__'] = __builtin__
100
100
101
101
102 def get_ipython():
102 def get_ipython():
103 # This will get replaced by the real thing once we start IPython below
103 # This will get replaced by the real thing once we start IPython below
104 return start_ipython()
104 return start_ipython()
105
105
106
106
107 def start_ipython():
107 def start_ipython():
108 """Start a global IPython shell, which we need for IPython-specific syntax.
108 """Start a global IPython shell, which we need for IPython-specific syntax.
109 """
109 """
110 global get_ipython
110 global get_ipython
111
111
112 # This function should only ever run once!
112 # This function should only ever run once!
113 if hasattr(start_ipython, 'already_called'):
113 if hasattr(start_ipython, 'already_called'):
114 return
114 return
115 start_ipython.already_called = True
115 start_ipython.already_called = True
116
116
117 # Ok, first time we're called, go ahead
117 # Ok, first time we're called, go ahead
118 from IPython.core import iplib
118 from IPython.core import iplib
119
119
120 def xsys(cmd):
120 def xsys(cmd):
121 """Execute a command and print its output.
121 """Execute a command and print its output.
122
122
123 This is just a convenience function to replace the IPython system call
123 This is just a convenience function to replace the IPython system call
124 with one that is more doctest-friendly.
124 with one that is more doctest-friendly.
125 """
125 """
126 cmd = _ip.var_expand(cmd,depth=1)
126 cmd = _ip.var_expand(cmd,depth=1)
127 sys.stdout.write(commands.getoutput(cmd))
127 sys.stdout.write(commands.getoutput(cmd))
128 sys.stdout.flush()
128 sys.stdout.flush()
129
129
130 # Store certain global objects that IPython modifies
130 # Store certain global objects that IPython modifies
131 _displayhook = sys.displayhook
131 _displayhook = sys.displayhook
132 _excepthook = sys.excepthook
132 _excepthook = sys.excepthook
133 _main = sys.modules.get('__main__')
133 _main = sys.modules.get('__main__')
134
134
135 # Create custom argv and namespaces for our IPython to be test-friendly
135 # Create custom argv and namespaces for our IPython to be test-friendly
136 config = tools.default_config()
136 config = tools.default_config()
137
137
138 # Create and initialize our test-friendly IPython instance.
138 # Create and initialize our test-friendly IPython instance.
139 shell = iplib.InteractiveShell(
139 shell = iplib.InteractiveShell(
140 parent=None, config=config,
140 config=config,
141 user_ns=ipnsdict(), user_global_ns={}
141 user_ns=ipnsdict(), user_global_ns={}
142 )
142 )
143
143
144 # A few more tweaks needed for playing nicely with doctests...
144 # A few more tweaks needed for playing nicely with doctests...
145
145
146 # These traps are normally only active for interactive use, set them
146 # These traps are normally only active for interactive use, set them
147 # permanently since we'll be mocking interactive sessions.
147 # permanently since we'll be mocking interactive sessions.
148 shell.builtin_trap.set()
148 shell.builtin_trap.set()
149
149
150 # Set error printing to stdout so nose can doctest exceptions
150 # Set error printing to stdout so nose can doctest exceptions
151 shell.InteractiveTB.out_stream = 'stdout'
151 shell.InteractiveTB.out_stream = 'stdout'
152
152
153 # Modify the IPython system call with one that uses getoutput, so that we
153 # Modify the IPython system call with one that uses getoutput, so that we
154 # can capture subcommands and print them to Python's stdout, otherwise the
154 # can capture subcommands and print them to Python's stdout, otherwise the
155 # doctest machinery would miss them.
155 # doctest machinery would miss them.
156 shell.system = xsys
156 shell.system = xsys
157
157
158 # IPython is ready, now clean up some global state...
158 # IPython is ready, now clean up some global state...
159
159
160 # Deactivate the various python system hooks added by ipython for
160 # Deactivate the various python system hooks added by ipython for
161 # interactive convenience so we don't confuse the doctest system
161 # interactive convenience so we don't confuse the doctest system
162 sys.modules['__main__'] = _main
162 sys.modules['__main__'] = _main
163 sys.displayhook = _displayhook
163 sys.displayhook = _displayhook
164 sys.excepthook = _excepthook
164 sys.excepthook = _excepthook
165
165
166 # So that ipython magics and aliases can be doctested (they work by making
166 # So that ipython magics and aliases can be doctested (they work by making
167 # a call into a global _ip object). Also make the top-level get_ipython
167 # a call into a global _ip object). Also make the top-level get_ipython
168 # now return this without recursively calling here again.
168 # now return this without recursively calling here again.
169 _ip = shell
169 _ip = shell
170 get_ipython = _ip.get_ipython
170 get_ipython = _ip.get_ipython
171 __builtin__._ip = _ip
171 __builtin__._ip = _ip
172 __builtin__.get_ipython = get_ipython
172 __builtin__.get_ipython = get_ipython
173
173
174 return _ip
174 return _ip
@@ -1,1025 +1,1047 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight Traits like module.
4 A lightweight Traits like module.
5
5
6 This is designed to provide a lightweight, simple, pure Python version of
6 This is designed to provide a lightweight, simple, pure Python version of
7 many of the capabilities of enthought.traits. This includes:
7 many of the capabilities of enthought.traits. This includes:
8
8
9 * Validation
9 * Validation
10 * Type specification with defaults
10 * Type specification with defaults
11 * Static and dynamic notification
11 * Static and dynamic notification
12 * Basic predefined types
12 * Basic predefined types
13 * An API that is similar to enthought.traits
13 * An API that is similar to enthought.traits
14
14
15 We don't support:
15 We don't support:
16
16
17 * Delegation
17 * Delegation
18 * Automatic GUI generation
18 * Automatic GUI generation
19 * A full set of trait types. Most importantly, we don't provide container
19 * A full set of trait types. Most importantly, we don't provide container
20 traits (list, dict, tuple) that can trigger notifications if their
20 traits (list, dict, tuple) that can trigger notifications if their
21 contents change.
21 contents change.
22 * API compatibility with enthought.traits
22 * API compatibility with enthought.traits
23
23
24 There are also some important difference in our design:
24 There are also some important difference in our design:
25
25
26 * enthought.traits does not validate default values. We do.
26 * enthought.traits does not validate default values. We do.
27
27
28 We choose to create this module because we need these capabilities, but
28 We choose to create this module because we need these capabilities, but
29 we need them to be pure Python so they work in all Python implementations,
29 we need them to be pure Python so they work in all Python implementations,
30 including Jython and IronPython.
30 including Jython and IronPython.
31
31
32 Authors:
32 Authors:
33
33
34 * Brian Granger
34 * Brian Granger
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
36 and is licensed under the BSD license. Also, many of the ideas also come
36 and is licensed under the BSD license. Also, many of the ideas also come
37 from enthought.traits even though our implementation is very different.
37 from enthought.traits even though our implementation is very different.
38 """
38 """
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Copyright (C) 2008-2009 The IPython Development Team
41 # Copyright (C) 2008-2009 The IPython Development Team
42 #
42 #
43 # Distributed under the terms of the BSD License. The full license is in
43 # Distributed under the terms of the BSD License. The full license is in
44 # the file COPYING, distributed as part of this software.
44 # the file COPYING, distributed as part of this software.
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Imports
48 # Imports
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51
51
52 import inspect
52 import inspect
53 import sys
53 import sys
54 import types
54 import types
55 from types import (
55 from types import (
56 InstanceType, ClassType, FunctionType,
56 InstanceType, ClassType, FunctionType,
57 ListType, TupleType
57 ListType, TupleType
58 )
58 )
59
59
60 def import_item(name):
60 def import_item(name):
61 """Import and return bar given the string foo.bar."""
61 """Import and return bar given the string foo.bar."""
62 package = '.'.join(name.split('.')[0:-1])
62 package = '.'.join(name.split('.')[0:-1])
63 obj = name.split('.')[-1]
63 obj = name.split('.')[-1]
64 execString = 'from %s import %s' % (package, obj)
64 execString = 'from %s import %s' % (package, obj)
65 try:
65 try:
66 exec execString
66 exec execString
67 except SyntaxError:
67 except SyntaxError:
68 raise ImportError("Invalid class specification: %s" % name)
68 raise ImportError("Invalid class specification: %s" % name)
69 exec 'temp = %s' % obj
69 exec 'temp = %s' % obj
70 return temp
70 return temp
71
71
72
72
73 ClassTypes = (ClassType, type)
73 ClassTypes = (ClassType, type)
74
74
75 SequenceTypes = (ListType, TupleType)
75 SequenceTypes = (ListType, TupleType)
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Basic classes
78 # Basic classes
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81
81
82 class NoDefaultSpecified ( object ): pass
82 class NoDefaultSpecified ( object ): pass
83 NoDefaultSpecified = NoDefaultSpecified()
83 NoDefaultSpecified = NoDefaultSpecified()
84
84
85
85
86 class Undefined ( object ): pass
86 class Undefined ( object ): pass
87 Undefined = Undefined()
87 Undefined = Undefined()
88
88
89 class TraitError(Exception):
89 class TraitError(Exception):
90 pass
90 pass
91
91
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93 # Utilities
93 # Utilities
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95
95
96
96
97 def class_of ( object ):
97 def class_of ( object ):
98 """ Returns a string containing the class name of an object with the
98 """ Returns a string containing the class name of an object with the
99 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
99 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
100 'a PlotValue').
100 'a PlotValue').
101 """
101 """
102 if isinstance( object, basestring ):
102 if isinstance( object, basestring ):
103 return add_article( object )
103 return add_article( object )
104
104
105 return add_article( object.__class__.__name__ )
105 return add_article( object.__class__.__name__ )
106
106
107
107
108 def add_article ( name ):
108 def add_article ( name ):
109 """ Returns a string containing the correct indefinite article ('a' or 'an')
109 """ Returns a string containing the correct indefinite article ('a' or 'an')
110 prefixed to the specified string.
110 prefixed to the specified string.
111 """
111 """
112 if name[:1].lower() in 'aeiou':
112 if name[:1].lower() in 'aeiou':
113 return 'an ' + name
113 return 'an ' + name
114
114
115 return 'a ' + name
115 return 'a ' + name
116
116
117
117
118 def repr_type(obj):
118 def repr_type(obj):
119 """ Return a string representation of a value and its type for readable
119 """ Return a string representation of a value and its type for readable
120 error messages.
120 error messages.
121 """
121 """
122 the_type = type(obj)
122 the_type = type(obj)
123 if the_type is InstanceType:
123 if the_type is InstanceType:
124 # Old-style class.
124 # Old-style class.
125 the_type = obj.__class__
125 the_type = obj.__class__
126 msg = '%r %r' % (obj, the_type)
126 msg = '%r %r' % (obj, the_type)
127 return msg
127 return msg
128
128
129
129
130 def parse_notifier_name(name):
130 def parse_notifier_name(name):
131 """Convert the name argument to a list of names.
131 """Convert the name argument to a list of names.
132
132
133 Examples
133 Examples
134 --------
134 --------
135
135
136 >>> parse_notifier_name('a')
136 >>> parse_notifier_name('a')
137 ['a']
137 ['a']
138 >>> parse_notifier_name(['a','b'])
138 >>> parse_notifier_name(['a','b'])
139 ['a', 'b']
139 ['a', 'b']
140 >>> parse_notifier_name(None)
140 >>> parse_notifier_name(None)
141 ['anytrait']
141 ['anytrait']
142 """
142 """
143 if isinstance(name, str):
143 if isinstance(name, str):
144 return [name]
144 return [name]
145 elif name is None:
145 elif name is None:
146 return ['anytrait']
146 return ['anytrait']
147 elif isinstance(name, (list, tuple)):
147 elif isinstance(name, (list, tuple)):
148 for n in name:
148 for n in name:
149 assert isinstance(n, str), "names must be strings"
149 assert isinstance(n, str), "names must be strings"
150 return name
150 return name
151
151
152
152
153 class _SimpleTest:
153 class _SimpleTest:
154 def __init__ ( self, value ): self.value = value
154 def __init__ ( self, value ): self.value = value
155 def __call__ ( self, test ):
155 def __call__ ( self, test ):
156 return test == self.value
156 return test == self.value
157 def __repr__(self):
157 def __repr__(self):
158 return "<SimpleTest(%r)" % self.value
158 return "<SimpleTest(%r)" % self.value
159 def __str__(self):
159 def __str__(self):
160 return self.__repr__()
160 return self.__repr__()
161
161
162
162
163 def getmembers(object, predicate=None):
163 def getmembers(object, predicate=None):
164 """A safe version of inspect.getmembers that handles missing attributes.
164 """A safe version of inspect.getmembers that handles missing attributes.
165
165
166 This is useful when there are descriptor based attributes that for
166 This is useful when there are descriptor based attributes that for
167 some reason raise AttributeError even though they exist. This happens
167 some reason raise AttributeError even though they exist. This happens
168 in zope.inteface with the __provides__ attribute.
168 in zope.inteface with the __provides__ attribute.
169 """
169 """
170 results = []
170 results = []
171 for key in dir(object):
171 for key in dir(object):
172 try:
172 try:
173 value = getattr(object, key)
173 value = getattr(object, key)
174 except AttributeError:
174 except AttributeError:
175 pass
175 pass
176 else:
176 else:
177 if not predicate or predicate(value):
177 if not predicate or predicate(value):
178 results.append((key, value))
178 results.append((key, value))
179 results.sort()
179 results.sort()
180 return results
180 return results
181
181
182
182
183 #-----------------------------------------------------------------------------
183 #-----------------------------------------------------------------------------
184 # Base TraitType for all traits
184 # Base TraitType for all traits
185 #-----------------------------------------------------------------------------
185 #-----------------------------------------------------------------------------
186
186
187
187
188 class TraitType(object):
188 class TraitType(object):
189 """A base class for all trait descriptors.
189 """A base class for all trait descriptors.
190
190
191 Notes
191 Notes
192 -----
192 -----
193 Our implementation of traits is based on Python's descriptor
193 Our implementation of traits is based on Python's descriptor
194 prototol. This class is the base class for all such descriptors. The
194 prototol. This class is the base class for all such descriptors. The
195 only magic we use is a custom metaclass for the main :class:`HasTraits`
195 only magic we use is a custom metaclass for the main :class:`HasTraits`
196 class that does the following:
196 class that does the following:
197
197
198 1. Sets the :attr:`name` attribute of every :class:`TraitType`
198 1. Sets the :attr:`name` attribute of every :class:`TraitType`
199 instance in the class dict to the name of the attribute.
199 instance in the class dict to the name of the attribute.
200 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
200 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
201 instance in the class dict to the *class* that declared the trait.
201 instance in the class dict to the *class* that declared the trait.
202 This is used by the :class:`This` trait to allow subclasses to
202 This is used by the :class:`This` trait to allow subclasses to
203 accept superclasses for :class:`This` values.
203 accept superclasses for :class:`This` values.
204 """
204 """
205
205
206
206
207 metadata = {}
207 metadata = {}
208 default_value = Undefined
208 default_value = Undefined
209 info_text = 'any value'
209 info_text = 'any value'
210
210
211 def __init__(self, default_value=NoDefaultSpecified, **metadata):
211 def __init__(self, default_value=NoDefaultSpecified, **metadata):
212 """Create a TraitType.
212 """Create a TraitType.
213 """
213 """
214 if default_value is not NoDefaultSpecified:
214 if default_value is not NoDefaultSpecified:
215 self.default_value = default_value
215 self.default_value = default_value
216
216
217 if len(metadata) > 0:
217 if len(metadata) > 0:
218 if len(self.metadata) > 0:
218 if len(self.metadata) > 0:
219 self._metadata = self.metadata.copy()
219 self._metadata = self.metadata.copy()
220 self._metadata.update(metadata)
220 self._metadata.update(metadata)
221 else:
221 else:
222 self._metadata = metadata
222 self._metadata = metadata
223 else:
223 else:
224 self._metadata = self.metadata
224 self._metadata = self.metadata
225
225
226 self.init()
226 self.init()
227
227
228 def init(self):
228 def init(self):
229 pass
229 pass
230
230
231 def get_default_value(self):
231 def get_default_value(self):
232 """Create a new instance of the default value."""
232 """Create a new instance of the default value."""
233 dv = self.default_value
233 dv = self.default_value
234 return dv
234 return dv
235
235
236 def instance_init(self, obj):
236 def instance_init(self, obj):
237 """This is called by :meth:`HasTraits.__new__` to finish init'ing.
237 """This is called by :meth:`HasTraits.__new__` to finish init'ing.
238
238
239 Some stages of initialization must be delayed until the parent
239 Some stages of initialization must be delayed until the parent
240 :class:`HasTraits` instance has been created. This method is
240 :class:`HasTraits` instance has been created. This method is
241 called in :meth:`HasTraits.__new__` after the instance has been
241 called in :meth:`HasTraits.__new__` after the instance has been
242 created.
242 created.
243
243
244 This method trigger the creation and validation of default values
244 This method trigger the creation and validation of default values
245 and also things like the resolution of str given class names in
245 and also things like the resolution of str given class names in
246 :class:`Type` and :class`Instance`.
246 :class:`Type` and :class`Instance`.
247
247
248 Parameters
248 Parameters
249 ----------
249 ----------
250 obj : :class:`HasTraits` instance
250 obj : :class:`HasTraits` instance
251 The parent :class:`HasTraits` instance that has just been
251 The parent :class:`HasTraits` instance that has just been
252 created.
252 created.
253 """
253 """
254 self.set_default_value(obj)
254 self.set_default_value(obj)
255
255
256 def set_default_value(self, obj):
256 def set_default_value(self, obj):
257 """Set the default value on a per instance basis.
257 """Set the default value on a per instance basis.
258
258
259 This method is called by :meth:`instance_init` to create and
259 This method is called by :meth:`instance_init` to create and
260 validate the default value. The creation and validation of
260 validate the default value. The creation and validation of
261 default values must be delayed until the parent :class:`HasTraits`
261 default values must be delayed until the parent :class:`HasTraits`
262 class has been instantiated.
262 class has been instantiated.
263 """
263 """
264 dv = self.get_default_value()
264 dv = self.get_default_value()
265 newdv = self._validate(obj, dv)
265 newdv = self._validate(obj, dv)
266 obj._trait_values[self.name] = newdv
266 obj._trait_values[self.name] = newdv
267
267
268 def __get__(self, obj, cls=None):
268 def __get__(self, obj, cls=None):
269 """Get the value of the trait by self.name for the instance.
269 """Get the value of the trait by self.name for the instance.
270
270
271 Default values are instantiated when :meth:`HasTraits.__new__`
271 Default values are instantiated when :meth:`HasTraits.__new__`
272 is called. Thus by the time this method gets called either the
272 is called. Thus by the time this method gets called either the
273 default value or a user defined value (they called :meth:`__set__`)
273 default value or a user defined value (they called :meth:`__set__`)
274 is in the :class:`HasTraits` instance.
274 is in the :class:`HasTraits` instance.
275 """
275 """
276 if obj is None:
276 if obj is None:
277 return self
277 return self
278 else:
278 else:
279 try:
279 try:
280 value = obj._trait_values[self.name]
280 value = obj._trait_values[self.name]
281 except:
281 except:
282 # HasTraits should call set_default_value to populate
282 # HasTraits should call set_default_value to populate
283 # this. So this should never be reached.
283 # this. So this should never be reached.
284 raise TraitError('Unexpected error in TraitType: '
284 raise TraitError('Unexpected error in TraitType: '
285 'default value not set properly')
285 'default value not set properly')
286 else:
286 else:
287 return value
287 return value
288
288
289 def __set__(self, obj, value):
289 def __set__(self, obj, value):
290 new_value = self._validate(obj, value)
290 new_value = self._validate(obj, value)
291 old_value = self.__get__(obj)
291 old_value = self.__get__(obj)
292 if old_value != new_value:
292 if old_value != new_value:
293 obj._trait_values[self.name] = new_value
293 obj._trait_values[self.name] = new_value
294 obj._notify_trait(self.name, old_value, new_value)
294 obj._notify_trait(self.name, old_value, new_value)
295
295
296 def _validate(self, obj, value):
296 def _validate(self, obj, value):
297 if hasattr(self, 'validate'):
297 if hasattr(self, 'validate'):
298 return self.validate(obj, value)
298 return self.validate(obj, value)
299 elif hasattr(self, 'is_valid_for'):
299 elif hasattr(self, 'is_valid_for'):
300 valid = self.is_valid_for(value)
300 valid = self.is_valid_for(value)
301 if valid:
301 if valid:
302 return value
302 return value
303 else:
303 else:
304 raise TraitError('invalid value for type: %r' % value)
304 raise TraitError('invalid value for type: %r' % value)
305 elif hasattr(self, 'value_for'):
305 elif hasattr(self, 'value_for'):
306 return self.value_for(value)
306 return self.value_for(value)
307 else:
307 else:
308 return value
308 return value
309
309
310 def info(self):
310 def info(self):
311 return self.info_text
311 return self.info_text
312
312
313 def error(self, obj, value):
313 def error(self, obj, value):
314 if obj is not None:
314 if obj is not None:
315 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
315 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
316 % (self.name, class_of(obj),
316 % (self.name, class_of(obj),
317 self.info(), repr_type(value))
317 self.info(), repr_type(value))
318 else:
318 else:
319 e = "The '%s' trait must be %s, but a value of %r was specified." \
319 e = "The '%s' trait must be %s, but a value of %r was specified." \
320 % (self.name, self.info(), repr_type(value))
320 % (self.name, self.info(), repr_type(value))
321 raise TraitError(e)
321 raise TraitError(e)
322
322
323 def get_metadata(self, key):
323 def get_metadata(self, key):
324 return getattr(self, '_metadata', {}).get(key, None)
324 return getattr(self, '_metadata', {}).get(key, None)
325
325
326 def set_metadata(self, key, value):
326 def set_metadata(self, key, value):
327 getattr(self, '_metadata', {})[key] = value
327 getattr(self, '_metadata', {})[key] = value
328
328
329
329
330 #-----------------------------------------------------------------------------
330 #-----------------------------------------------------------------------------
331 # The HasTraits implementation
331 # The HasTraits implementation
332 #-----------------------------------------------------------------------------
332 #-----------------------------------------------------------------------------
333
333
334
334
335 class MetaHasTraits(type):
335 class MetaHasTraits(type):
336 """A metaclass for HasTraits.
336 """A metaclass for HasTraits.
337
337
338 This metaclass makes sure that any TraitType class attributes are
338 This metaclass makes sure that any TraitType class attributes are
339 instantiated and sets their name attribute.
339 instantiated and sets their name attribute.
340 """
340 """
341
341
342 def __new__(mcls, name, bases, classdict):
342 def __new__(mcls, name, bases, classdict):
343 """Create the HasTraits class.
343 """Create the HasTraits class.
344
344
345 This instantiates all TraitTypes in the class dict and sets their
345 This instantiates all TraitTypes in the class dict and sets their
346 :attr:`name` attribute.
346 :attr:`name` attribute.
347 """
347 """
348 # print "MetaHasTraitlets (mcls, name): ", mcls, name
348 # print "MetaHasTraitlets (mcls, name): ", mcls, name
349 # print "MetaHasTraitlets (bases): ", bases
349 # print "MetaHasTraitlets (bases): ", bases
350 # print "MetaHasTraitlets (classdict): ", classdict
350 # print "MetaHasTraitlets (classdict): ", classdict
351 for k,v in classdict.iteritems():
351 for k,v in classdict.iteritems():
352 if isinstance(v, TraitType):
352 if isinstance(v, TraitType):
353 v.name = k
353 v.name = k
354 elif inspect.isclass(v):
354 elif inspect.isclass(v):
355 if issubclass(v, TraitType):
355 if issubclass(v, TraitType):
356 vinst = v()
356 vinst = v()
357 vinst.name = k
357 vinst.name = k
358 classdict[k] = vinst
358 classdict[k] = vinst
359 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
359 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
360
360
361 def __init__(cls, name, bases, classdict):
361 def __init__(cls, name, bases, classdict):
362 """Finish initializing the HasTraits class.
362 """Finish initializing the HasTraits class.
363
363
364 This sets the :attr:`this_class` attribute of each TraitType in the
364 This sets the :attr:`this_class` attribute of each TraitType in the
365 class dict to the newly created class ``cls``.
365 class dict to the newly created class ``cls``.
366 """
366 """
367 for k, v in classdict.iteritems():
367 for k, v in classdict.iteritems():
368 if isinstance(v, TraitType):
368 if isinstance(v, TraitType):
369 v.this_class = cls
369 v.this_class = cls
370 super(MetaHasTraits, cls).__init__(name, bases, classdict)
370 super(MetaHasTraits, cls).__init__(name, bases, classdict)
371
371
372 class HasTraits(object):
372 class HasTraits(object):
373
373
374 __metaclass__ = MetaHasTraits
374 __metaclass__ = MetaHasTraits
375
375
376 def __new__(cls, *args, **kw):
376 def __new__(cls, *args, **kw):
377 # This is needed because in Python 2.6 object.__new__ only accepts
377 # This is needed because in Python 2.6 object.__new__ only accepts
378 # the cls argument.
378 # the cls argument.
379 new_meth = super(HasTraits, cls).__new__
379 new_meth = super(HasTraits, cls).__new__
380 if new_meth is object.__new__:
380 if new_meth is object.__new__:
381 inst = new_meth(cls)
381 inst = new_meth(cls)
382 else:
382 else:
383 inst = new_meth(cls, *args, **kw)
383 inst = new_meth(cls, *args, **kw)
384 inst._trait_values = {}
384 inst._trait_values = {}
385 inst._trait_notifiers = {}
385 inst._trait_notifiers = {}
386 # Here we tell all the TraitType instances to set their default
386 # Here we tell all the TraitType instances to set their default
387 # values on the instance.
387 # values on the instance.
388 for key in dir(cls):
388 for key in dir(cls):
389 # Some descriptors raise AttributeError like zope.interface's
389 # Some descriptors raise AttributeError like zope.interface's
390 # __provides__ attributes even though they exist. This causes
390 # __provides__ attributes even though they exist. This causes
391 # AttributeErrors even though they are listed in dir(cls).
391 # AttributeErrors even though they are listed in dir(cls).
392 try:
392 try:
393 value = getattr(cls, key)
393 value = getattr(cls, key)
394 except AttributeError:
394 except AttributeError:
395 pass
395 pass
396 else:
396 else:
397 if isinstance(value, TraitType):
397 if isinstance(value, TraitType):
398 value.instance_init(inst)
398 value.instance_init(inst)
399
399
400 return inst
400 return inst
401
401
402 # def __init__(self):
402 # def __init__(self):
403 # self._trait_values = {}
403 # self._trait_values = {}
404 # self._trait_notifiers = {}
404 # self._trait_notifiers = {}
405
405
406 def _notify_trait(self, name, old_value, new_value):
406 def _notify_trait(self, name, old_value, new_value):
407
407
408 # First dynamic ones
408 # First dynamic ones
409 callables = self._trait_notifiers.get(name,[])
409 callables = self._trait_notifiers.get(name,[])
410 more_callables = self._trait_notifiers.get('anytrait',[])
410 more_callables = self._trait_notifiers.get('anytrait',[])
411 callables.extend(more_callables)
411 callables.extend(more_callables)
412
412
413 # Now static ones
413 # Now static ones
414 try:
414 try:
415 cb = getattr(self, '_%s_changed' % name)
415 cb = getattr(self, '_%s_changed' % name)
416 except:
416 except:
417 pass
417 pass
418 else:
418 else:
419 callables.append(cb)
419 callables.append(cb)
420
420
421 # Call them all now
421 # Call them all now
422 for c in callables:
422 for c in callables:
423 # Traits catches and logs errors here. I allow them to raise
423 # Traits catches and logs errors here. I allow them to raise
424 if callable(c):
424 if callable(c):
425 argspec = inspect.getargspec(c)
425 argspec = inspect.getargspec(c)
426 nargs = len(argspec[0])
426 nargs = len(argspec[0])
427 # Bound methods have an additional 'self' argument
427 # Bound methods have an additional 'self' argument
428 # I don't know how to treat unbound methods, but they
428 # I don't know how to treat unbound methods, but they
429 # can't really be used for callbacks.
429 # can't really be used for callbacks.
430 if isinstance(c, types.MethodType):
430 if isinstance(c, types.MethodType):
431 offset = -1
431 offset = -1
432 else:
432 else:
433 offset = 0
433 offset = 0
434 if nargs + offset == 0:
434 if nargs + offset == 0:
435 c()
435 c()
436 elif nargs + offset == 1:
436 elif nargs + offset == 1:
437 c(name)
437 c(name)
438 elif nargs + offset == 2:
438 elif nargs + offset == 2:
439 c(name, new_value)
439 c(name, new_value)
440 elif nargs + offset == 3:
440 elif nargs + offset == 3:
441 c(name, old_value, new_value)
441 c(name, old_value, new_value)
442 else:
442 else:
443 raise TraitError('a trait changed callback '
443 raise TraitError('a trait changed callback '
444 'must have 0-3 arguments.')
444 'must have 0-3 arguments.')
445 else:
445 else:
446 raise TraitError('a trait changed callback '
446 raise TraitError('a trait changed callback '
447 'must be callable.')
447 'must be callable.')
448
448
449
449
450 def _add_notifiers(self, handler, name):
450 def _add_notifiers(self, handler, name):
451 if not self._trait_notifiers.has_key(name):
451 if not self._trait_notifiers.has_key(name):
452 nlist = []
452 nlist = []
453 self._trait_notifiers[name] = nlist
453 self._trait_notifiers[name] = nlist
454 else:
454 else:
455 nlist = self._trait_notifiers[name]
455 nlist = self._trait_notifiers[name]
456 if handler not in nlist:
456 if handler not in nlist:
457 nlist.append(handler)
457 nlist.append(handler)
458
458
459 def _remove_notifiers(self, handler, name):
459 def _remove_notifiers(self, handler, name):
460 if self._trait_notifiers.has_key(name):
460 if self._trait_notifiers.has_key(name):
461 nlist = self._trait_notifiers[name]
461 nlist = self._trait_notifiers[name]
462 try:
462 try:
463 index = nlist.index(handler)
463 index = nlist.index(handler)
464 except ValueError:
464 except ValueError:
465 pass
465 pass
466 else:
466 else:
467 del nlist[index]
467 del nlist[index]
468
468
469 def on_trait_change(self, handler, name=None, remove=False):
469 def on_trait_change(self, handler, name=None, remove=False):
470 """Setup a handler to be called when a trait changes.
470 """Setup a handler to be called when a trait changes.
471
471
472 This is used to setup dynamic notifications of trait changes.
472 This is used to setup dynamic notifications of trait changes.
473
473
474 Static handlers can be created by creating methods on a HasTraits
474 Static handlers can be created by creating methods on a HasTraits
475 subclass with the naming convention '_[traitname]_changed'. Thus,
475 subclass with the naming convention '_[traitname]_changed'. Thus,
476 to create static handler for the trait 'a', create the method
476 to create static handler for the trait 'a', create the method
477 _a_changed(self, name, old, new) (fewer arguments can be used, see
477 _a_changed(self, name, old, new) (fewer arguments can be used, see
478 below).
478 below).
479
479
480 Parameters
480 Parameters
481 ----------
481 ----------
482 handler : callable
482 handler : callable
483 A callable that is called when a trait changes. Its
483 A callable that is called when a trait changes. Its
484 signature can be handler(), handler(name), handler(name, new)
484 signature can be handler(), handler(name), handler(name, new)
485 or handler(name, old, new).
485 or handler(name, old, new).
486 name : list, str, None
486 name : list, str, None
487 If None, the handler will apply to all traits. If a list
487 If None, the handler will apply to all traits. If a list
488 of str, handler will apply to all names in the list. If a
488 of str, handler will apply to all names in the list. If a
489 str, the handler will apply just to that name.
489 str, the handler will apply just to that name.
490 remove : bool
490 remove : bool
491 If False (the default), then install the handler. If True
491 If False (the default), then install the handler. If True
492 then unintall it.
492 then unintall it.
493 """
493 """
494 if remove:
494 if remove:
495 names = parse_notifier_name(name)
495 names = parse_notifier_name(name)
496 for n in names:
496 for n in names:
497 self._remove_notifiers(handler, n)
497 self._remove_notifiers(handler, n)
498 else:
498 else:
499 names = parse_notifier_name(name)
499 names = parse_notifier_name(name)
500 for n in names:
500 for n in names:
501 self._add_notifiers(handler, n)
501 self._add_notifiers(handler, n)
502
502
503 def trait_names(self, **metadata):
503 def trait_names(self, **metadata):
504 """Get a list of all the names of this classes traits."""
504 """Get a list of all the names of this classes traits."""
505 return self.traits(**metadata).keys()
505 return self.traits(**metadata).keys()
506
506
507 def traits(self, **metadata):
507 def traits(self, **metadata):
508 """Get a list of all the traits of this class.
508 """Get a list of all the traits of this class.
509
509
510 The TraitTypes returned don't know anything about the values
510 The TraitTypes returned don't know anything about the values
511 that the various HasTrait's instances are holding.
511 that the various HasTrait's instances are holding.
512
512
513 This follows the same algorithm as traits does and does not allow
513 This follows the same algorithm as traits does and does not allow
514 for any simple way of specifying merely that a metadata name
514 for any simple way of specifying merely that a metadata name
515 exists, but has any value. This is because get_metadata returns
515 exists, but has any value. This is because get_metadata returns
516 None if a metadata key doesn't exist.
516 None if a metadata key doesn't exist.
517 """
517 """
518 traits = dict([memb for memb in getmembers(self.__class__) if \
518 traits = dict([memb for memb in getmembers(self.__class__) if \
519 isinstance(memb[1], TraitType)])
519 isinstance(memb[1], TraitType)])
520
520
521 if len(metadata) == 0:
521 if len(metadata) == 0:
522 return traits
522 return traits
523
523
524 for meta_name, meta_eval in metadata.items():
524 for meta_name, meta_eval in metadata.items():
525 if type(meta_eval) is not FunctionType:
525 if type(meta_eval) is not FunctionType:
526 metadata[meta_name] = _SimpleTest(meta_eval)
526 metadata[meta_name] = _SimpleTest(meta_eval)
527
527
528 result = {}
528 result = {}
529 for name, trait in traits.items():
529 for name, trait in traits.items():
530 for meta_name, meta_eval in metadata.items():
530 for meta_name, meta_eval in metadata.items():
531 if not meta_eval(trait.get_metadata(meta_name)):
531 if not meta_eval(trait.get_metadata(meta_name)):
532 break
532 break
533 else:
533 else:
534 result[name] = trait
534 result[name] = trait
535
535
536 return result
536 return result
537
537
538 def trait_metadata(self, traitname, key):
538 def trait_metadata(self, traitname, key):
539 """Get metadata values for trait by key."""
539 """Get metadata values for trait by key."""
540 try:
540 try:
541 trait = getattr(self.__class__, traitname)
541 trait = getattr(self.__class__, traitname)
542 except AttributeError:
542 except AttributeError:
543 raise TraitError("Class %s does not have a trait named %s" %
543 raise TraitError("Class %s does not have a trait named %s" %
544 (self.__class__.__name__, traitname))
544 (self.__class__.__name__, traitname))
545 else:
545 else:
546 return trait.get_metadata(key)
546 return trait.get_metadata(key)
547
547
548 #-----------------------------------------------------------------------------
548 #-----------------------------------------------------------------------------
549 # Actual TraitTypes implementations/subclasses
549 # Actual TraitTypes implementations/subclasses
550 #-----------------------------------------------------------------------------
550 #-----------------------------------------------------------------------------
551
551
552 #-----------------------------------------------------------------------------
552 #-----------------------------------------------------------------------------
553 # TraitTypes subclasses for handling classes and instances of classes
553 # TraitTypes subclasses for handling classes and instances of classes
554 #-----------------------------------------------------------------------------
554 #-----------------------------------------------------------------------------
555
555
556
556
557 class ClassBasedTraitType(TraitType):
557 class ClassBasedTraitType(TraitType):
558 """A trait with error reporting for Type, Instance and This."""
558 """A trait with error reporting for Type, Instance and This."""
559
559
560 def error(self, obj, value):
560 def error(self, obj, value):
561 kind = type(value)
561 kind = type(value)
562 if kind is InstanceType:
562 if kind is InstanceType:
563 msg = 'class %s' % value.__class__.__name__
563 msg = 'class %s' % value.__class__.__name__
564 else:
564 else:
565 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
565 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
566
566
567 super(ClassBasedTraitType, self).error(obj, msg)
567 super(ClassBasedTraitType, self).error(obj, msg)
568
568
569
569
570 class Type(ClassBasedTraitType):
570 class Type(ClassBasedTraitType):
571 """A trait whose value must be a subclass of a specified class."""
571 """A trait whose value must be a subclass of a specified class."""
572
572
573 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
573 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
574 """Construct a Type trait
574 """Construct a Type trait
575
575
576 A Type trait specifies that its values must be subclasses of
576 A Type trait specifies that its values must be subclasses of
577 a particular class.
577 a particular class.
578
578
579 If only ``default_value`` is given, it is used for the ``klass`` as
579 If only ``default_value`` is given, it is used for the ``klass`` as
580 well.
580 well.
581
581
582 Parameters
582 Parameters
583 ----------
583 ----------
584 default_value : class, str or None
584 default_value : class, str or None
585 The default value must be a subclass of klass. If an str,
585 The default value must be a subclass of klass. If an str,
586 the str must be a fully specified class name, like 'foo.bar.Bah'.
586 the str must be a fully specified class name, like 'foo.bar.Bah'.
587 The string is resolved into real class, when the parent
587 The string is resolved into real class, when the parent
588 :class:`HasTraits` class is instantiated.
588 :class:`HasTraits` class is instantiated.
589 klass : class, str, None
589 klass : class, str, None
590 Values of this trait must be a subclass of klass. The klass
590 Values of this trait must be a subclass of klass. The klass
591 may be specified in a string like: 'foo.bar.MyClass'.
591 may be specified in a string like: 'foo.bar.MyClass'.
592 The string is resolved into real class, when the parent
592 The string is resolved into real class, when the parent
593 :class:`HasTraits` class is instantiated.
593 :class:`HasTraits` class is instantiated.
594 allow_none : boolean
594 allow_none : boolean
595 Indicates whether None is allowed as an assignable value. Even if
595 Indicates whether None is allowed as an assignable value. Even if
596 ``False``, the default value may be ``None``.
596 ``False``, the default value may be ``None``.
597 """
597 """
598 if default_value is None:
598 if default_value is None:
599 if klass is None:
599 if klass is None:
600 klass = object
600 klass = object
601 elif klass is None:
601 elif klass is None:
602 klass = default_value
602 klass = default_value
603
603
604 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
604 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
605 raise TraitError("A Type trait must specify a class.")
605 raise TraitError("A Type trait must specify a class.")
606
606
607 self.klass = klass
607 self.klass = klass
608 self._allow_none = allow_none
608 self._allow_none = allow_none
609
609
610 super(Type, self).__init__(default_value, **metadata)
610 super(Type, self).__init__(default_value, **metadata)
611
611
612 def validate(self, obj, value):
612 def validate(self, obj, value):
613 """Validates that the value is a valid object instance."""
613 """Validates that the value is a valid object instance."""
614 try:
614 try:
615 if issubclass(value, self.klass):
615 if issubclass(value, self.klass):
616 return value
616 return value
617 except:
617 except:
618 if (value is None) and (self._allow_none):
618 if (value is None) and (self._allow_none):
619 return value
619 return value
620
620
621 self.error(obj, value)
621 self.error(obj, value)
622
622
623 def info(self):
623 def info(self):
624 """ Returns a description of the trait."""
624 """ Returns a description of the trait."""
625 if isinstance(self.klass, basestring):
625 if isinstance(self.klass, basestring):
626 klass = self.klass
626 klass = self.klass
627 else:
627 else:
628 klass = self.klass.__name__
628 klass = self.klass.__name__
629 result = 'a subclass of ' + klass
629 result = 'a subclass of ' + klass
630 if self._allow_none:
630 if self._allow_none:
631 return result + ' or None'
631 return result + ' or None'
632 return result
632 return result
633
633
634 def instance_init(self, obj):
634 def instance_init(self, obj):
635 self._resolve_classes()
635 self._resolve_classes()
636 super(Type, self).instance_init(obj)
636 super(Type, self).instance_init(obj)
637
637
638 def _resolve_classes(self):
638 def _resolve_classes(self):
639 if isinstance(self.klass, basestring):
639 if isinstance(self.klass, basestring):
640 self.klass = import_item(self.klass)
640 self.klass = import_item(self.klass)
641 if isinstance(self.default_value, basestring):
641 if isinstance(self.default_value, basestring):
642 self.default_value = import_item(self.default_value)
642 self.default_value = import_item(self.default_value)
643
643
644 def get_default_value(self):
644 def get_default_value(self):
645 return self.default_value
645 return self.default_value
646
646
647
647
648 class DefaultValueGenerator(object):
648 class DefaultValueGenerator(object):
649 """A class for generating new default value instances."""
649 """A class for generating new default value instances."""
650
650
651 def __init__(self, *args, **kw):
651 def __init__(self, *args, **kw):
652 self.args = args
652 self.args = args
653 self.kw = kw
653 self.kw = kw
654
654
655 def generate(self, klass):
655 def generate(self, klass):
656 return klass(*self.args, **self.kw)
656 return klass(*self.args, **self.kw)
657
657
658
658
659 class Instance(ClassBasedTraitType):
659 class Instance(ClassBasedTraitType):
660 """A trait whose value must be an instance of a specified class.
660 """A trait whose value must be an instance of a specified class.
661
661
662 The value can also be an instance of a subclass of the specified class.
662 The value can also be an instance of a subclass of the specified class.
663 """
663 """
664
664
665 def __init__(self, klass=None, args=None, kw=None,
665 def __init__(self, klass=None, args=None, kw=None,
666 allow_none=True, **metadata ):
666 allow_none=True, **metadata ):
667 """Construct an Instance trait.
667 """Construct an Instance trait.
668
668
669 This trait allows values that are instances of a particular
669 This trait allows values that are instances of a particular
670 class or its sublclasses. Our implementation is quite different
670 class or its sublclasses. Our implementation is quite different
671 from that of enthough.traits as we don't allow instances to be used
671 from that of enthough.traits as we don't allow instances to be used
672 for klass and we handle the ``args`` and ``kw`` arguments differently.
672 for klass and we handle the ``args`` and ``kw`` arguments differently.
673
673
674 Parameters
674 Parameters
675 ----------
675 ----------
676 klass : class, str
676 klass : class, str
677 The class that forms the basis for the trait. Class names
677 The class that forms the basis for the trait. Class names
678 can also be specified as strings, like 'foo.bar.Bar'.
678 can also be specified as strings, like 'foo.bar.Bar'.
679 args : tuple
679 args : tuple
680 Positional arguments for generating the default value.
680 Positional arguments for generating the default value.
681 kw : dict
681 kw : dict
682 Keyword arguments for generating the default value.
682 Keyword arguments for generating the default value.
683 allow_none : bool
683 allow_none : bool
684 Indicates whether None is allowed as a value.
684 Indicates whether None is allowed as a value.
685
685
686 Default Value
686 Default Value
687 -------------
687 -------------
688 If both ``args`` and ``kw`` are None, then the default value is None.
688 If both ``args`` and ``kw`` are None, then the default value is None.
689 If ``args`` is a tuple and ``kw`` is a dict, then the default is
689 If ``args`` is a tuple and ``kw`` is a dict, then the default is
690 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
690 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
691 not (but not both), None is replace by ``()`` or ``{}``.
691 not (but not both), None is replace by ``()`` or ``{}``.
692 """
692 """
693
693
694 self._allow_none = allow_none
694 self._allow_none = allow_none
695
695
696 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
696 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
697 raise TraitError('The klass argument must be a class'
697 raise TraitError('The klass argument must be a class'
698 ' you gave: %r' % klass)
698 ' you gave: %r' % klass)
699 self.klass = klass
699 self.klass = klass
700
700
701 # self.klass is a class, so handle default_value
701 # self.klass is a class, so handle default_value
702 if args is None and kw is None:
702 if args is None and kw is None:
703 default_value = None
703 default_value = None
704 else:
704 else:
705 if args is None:
705 if args is None:
706 # kw is not None
706 # kw is not None
707 args = ()
707 args = ()
708 elif kw is None:
708 elif kw is None:
709 # args is not None
709 # args is not None
710 kw = {}
710 kw = {}
711
711
712 if not isinstance(kw, dict):
712 if not isinstance(kw, dict):
713 raise TraitError("The 'kw' argument must be a dict or None.")
713 raise TraitError("The 'kw' argument must be a dict or None.")
714 if not isinstance(args, tuple):
714 if not isinstance(args, tuple):
715 raise TraitError("The 'args' argument must be a tuple or None.")
715 raise TraitError("The 'args' argument must be a tuple or None.")
716
716
717 default_value = DefaultValueGenerator(*args, **kw)
717 default_value = DefaultValueGenerator(*args, **kw)
718
718
719 super(Instance, self).__init__(default_value, **metadata)
719 super(Instance, self).__init__(default_value, **metadata)
720
720
721 def validate(self, obj, value):
721 def validate(self, obj, value):
722 if value is None:
722 if value is None:
723 if self._allow_none:
723 if self._allow_none:
724 return value
724 return value
725 self.error(obj, value)
725 self.error(obj, value)
726
726
727 if isinstance(value, self.klass):
727 if isinstance(value, self.klass):
728 return value
728 return value
729 else:
729 else:
730 self.error(obj, value)
730 self.error(obj, value)
731
731
732 def info(self):
732 def info(self):
733 if isinstance(self.klass, basestring):
733 if isinstance(self.klass, basestring):
734 klass = self.klass
734 klass = self.klass
735 else:
735 else:
736 klass = self.klass.__name__
736 klass = self.klass.__name__
737 result = class_of(klass)
737 result = class_of(klass)
738 if self._allow_none:
738 if self._allow_none:
739 return result + ' or None'
739 return result + ' or None'
740
740
741 return result
741 return result
742
742
743 def instance_init(self, obj):
743 def instance_init(self, obj):
744 self._resolve_classes()
744 self._resolve_classes()
745 super(Instance, self).instance_init(obj)
745 super(Instance, self).instance_init(obj)
746
746
747 def _resolve_classes(self):
747 def _resolve_classes(self):
748 if isinstance(self.klass, basestring):
748 if isinstance(self.klass, basestring):
749 self.klass = import_item(self.klass)
749 self.klass = import_item(self.klass)
750
750
751 def get_default_value(self):
751 def get_default_value(self):
752 """Instantiate a default value instance.
752 """Instantiate a default value instance.
753
753
754 This is called when the containing HasTraits classes'
754 This is called when the containing HasTraits classes'
755 :meth:`__new__` method is called to ensure that a unique instance
755 :meth:`__new__` method is called to ensure that a unique instance
756 is created for each HasTraits instance.
756 is created for each HasTraits instance.
757 """
757 """
758 dv = self.default_value
758 dv = self.default_value
759 if isinstance(dv, DefaultValueGenerator):
759 if isinstance(dv, DefaultValueGenerator):
760 return dv.generate(self.klass)
760 return dv.generate(self.klass)
761 else:
761 else:
762 return dv
762 return dv
763
763
764
764
765 class This(ClassBasedTraitType):
765 class This(ClassBasedTraitType):
766 """A trait for instances of the class containing this trait.
766 """A trait for instances of the class containing this trait.
767
767
768 Because how how and when class bodies are executed, the ``This``
768 Because how how and when class bodies are executed, the ``This``
769 trait can only have a default value of None. This, and because we
769 trait can only have a default value of None. This, and because we
770 always validate default values, ``allow_none`` is *always* true.
770 always validate default values, ``allow_none`` is *always* true.
771 """
771 """
772
772
773 info_text = 'an instance of the same type as the receiver or None'
773 info_text = 'an instance of the same type as the receiver or None'
774
774
775 def __init__(self, **metadata):
775 def __init__(self, **metadata):
776 super(This, self).__init__(None, **metadata)
776 super(This, self).__init__(None, **metadata)
777
777
778 def validate(self, obj, value):
778 def validate(self, obj, value):
779 # What if value is a superclass of obj.__class__? This is
779 # What if value is a superclass of obj.__class__? This is
780 # complicated if it was the superclass that defined the This
780 # complicated if it was the superclass that defined the This
781 # trait.
781 # trait.
782 if isinstance(value, self.this_class) or (value is None):
782 if isinstance(value, self.this_class) or (value is None):
783 return value
783 return value
784 else:
784 else:
785 self.error(obj, value)
785 self.error(obj, value)
786
786
787
787
788 #-----------------------------------------------------------------------------
788 #-----------------------------------------------------------------------------
789 # Basic TraitTypes implementations/subclasses
789 # Basic TraitTypes implementations/subclasses
790 #-----------------------------------------------------------------------------
790 #-----------------------------------------------------------------------------
791
791
792
792
793 class Any(TraitType):
793 class Any(TraitType):
794 default_value = None
794 default_value = None
795 info_text = 'any value'
795 info_text = 'any value'
796
796
797
797
798 class Int(TraitType):
798 class Int(TraitType):
799 """A integer trait."""
799 """A integer trait."""
800
800
801 evaluate = int
801 evaluate = int
802 default_value = 0
802 default_value = 0
803 info_text = 'an integer'
803 info_text = 'an integer'
804
804
805 def validate(self, obj, value):
805 def validate(self, obj, value):
806 if isinstance(value, int):
806 if isinstance(value, int):
807 return value
807 return value
808 self.error(obj, value)
808 self.error(obj, value)
809
809
810 class CInt(Int):
810 class CInt(Int):
811 """A casting version of the int trait."""
811 """A casting version of the int trait."""
812
812
813 def validate(self, obj, value):
813 def validate(self, obj, value):
814 try:
814 try:
815 return int(value)
815 return int(value)
816 except:
816 except:
817 self.error(obj, value)
817 self.error(obj, value)
818
818
819
819
820 class Long(TraitType):
820 class Long(TraitType):
821 """A long integer trait."""
821 """A long integer trait."""
822
822
823 evaluate = long
823 evaluate = long
824 default_value = 0L
824 default_value = 0L
825 info_text = 'a long'
825 info_text = 'a long'
826
826
827 def validate(self, obj, value):
827 def validate(self, obj, value):
828 if isinstance(value, long):
828 if isinstance(value, long):
829 return value
829 return value
830 if isinstance(value, int):
830 if isinstance(value, int):
831 return long(value)
831 return long(value)
832 self.error(obj, value)
832 self.error(obj, value)
833
833
834
834
835 class CLong(Long):
835 class CLong(Long):
836 """A casting version of the long integer trait."""
836 """A casting version of the long integer trait."""
837
837
838 def validate(self, obj, value):
838 def validate(self, obj, value):
839 try:
839 try:
840 return long(value)
840 return long(value)
841 except:
841 except:
842 self.error(obj, value)
842 self.error(obj, value)
843
843
844
844
845 class Float(TraitType):
845 class Float(TraitType):
846 """A float trait."""
846 """A float trait."""
847
847
848 evaluate = float
848 evaluate = float
849 default_value = 0.0
849 default_value = 0.0
850 info_text = 'a float'
850 info_text = 'a float'
851
851
852 def validate(self, obj, value):
852 def validate(self, obj, value):
853 if isinstance(value, float):
853 if isinstance(value, float):
854 return value
854 return value
855 if isinstance(value, int):
855 if isinstance(value, int):
856 return float(value)
856 return float(value)
857 self.error(obj, value)
857 self.error(obj, value)
858
858
859
859
860 class CFloat(Float):
860 class CFloat(Float):
861 """A casting version of the float trait."""
861 """A casting version of the float trait."""
862
862
863 def validate(self, obj, value):
863 def validate(self, obj, value):
864 try:
864 try:
865 return float(value)
865 return float(value)
866 except:
866 except:
867 self.error(obj, value)
867 self.error(obj, value)
868
868
869 class Complex(TraitType):
869 class Complex(TraitType):
870 """A trait for complex numbers."""
870 """A trait for complex numbers."""
871
871
872 evaluate = complex
872 evaluate = complex
873 default_value = 0.0 + 0.0j
873 default_value = 0.0 + 0.0j
874 info_text = 'a complex number'
874 info_text = 'a complex number'
875
875
876 def validate(self, obj, value):
876 def validate(self, obj, value):
877 if isinstance(value, complex):
877 if isinstance(value, complex):
878 return value
878 return value
879 if isinstance(value, (float, int)):
879 if isinstance(value, (float, int)):
880 return complex(value)
880 return complex(value)
881 self.error(obj, value)
881 self.error(obj, value)
882
882
883
883
884 class CComplex(Complex):
884 class CComplex(Complex):
885 """A casting version of the complex number trait."""
885 """A casting version of the complex number trait."""
886
886
887 def validate (self, obj, value):
887 def validate (self, obj, value):
888 try:
888 try:
889 return complex(value)
889 return complex(value)
890 except:
890 except:
891 self.error(obj, value)
891 self.error(obj, value)
892
892
893
893
894 class Str(TraitType):
894 class Str(TraitType):
895 """A trait for strings."""
895 """A trait for strings."""
896
896
897 evaluate = lambda x: x
897 evaluate = lambda x: x
898 default_value = ''
898 default_value = ''
899 info_text = 'a string'
899 info_text = 'a string'
900
900
901 def validate(self, obj, value):
901 def validate(self, obj, value):
902 if isinstance(value, str):
902 if isinstance(value, str):
903 return value
903 return value
904 self.error(obj, value)
904 self.error(obj, value)
905
905
906
906
907 class CStr(Str):
907 class CStr(Str):
908 """A casting version of the string trait."""
908 """A casting version of the string trait."""
909
909
910 def validate(self, obj, value):
910 def validate(self, obj, value):
911 try:
911 try:
912 return str(value)
912 return str(value)
913 except:
913 except:
914 try:
914 try:
915 return unicode(value)
915 return unicode(value)
916 except:
916 except:
917 self.error(obj, value)
917 self.error(obj, value)
918
918
919
919
920 class Unicode(TraitType):
920 class Unicode(TraitType):
921 """A trait for unicode strings."""
921 """A trait for unicode strings."""
922
922
923 evaluate = unicode
923 evaluate = unicode
924 default_value = u''
924 default_value = u''
925 info_text = 'a unicode string'
925 info_text = 'a unicode string'
926
926
927 def validate(self, obj, value):
927 def validate(self, obj, value):
928 if isinstance(value, unicode):
928 if isinstance(value, unicode):
929 return value
929 return value
930 if isinstance(value, str):
930 if isinstance(value, str):
931 return unicode(value)
931 return unicode(value)
932 self.error(obj, value)
932 self.error(obj, value)
933
933
934
934
935 class CUnicode(Unicode):
935 class CUnicode(Unicode):
936 """A casting version of the unicode trait."""
936 """A casting version of the unicode trait."""
937
937
938 def validate(self, obj, value):
938 def validate(self, obj, value):
939 try:
939 try:
940 return unicode(value)
940 return unicode(value)
941 except:
941 except:
942 self.error(obj, value)
942 self.error(obj, value)
943
943
944
944
945 class Bool(TraitType):
945 class Bool(TraitType):
946 """A boolean (True, False) trait."""
946 """A boolean (True, False) trait."""
947 evaluate = bool
947 evaluate = bool
948 default_value = False
948 default_value = False
949 info_text = 'a boolean'
949 info_text = 'a boolean'
950
950
951 def validate(self, obj, value):
951 def validate(self, obj, value):
952 if isinstance(value, bool):
952 if isinstance(value, bool):
953 return value
953 return value
954 self.error(obj, value)
954 self.error(obj, value)
955
955
956
956
957 class CBool(Bool):
957 class CBool(Bool):
958 """A casting version of the boolean trait."""
958 """A casting version of the boolean trait."""
959
959
960 def validate(self, obj, value):
960 def validate(self, obj, value):
961 try:
961 try:
962 return bool(value)
962 return bool(value)
963 except:
963 except:
964 self.error(obj, value)
964 self.error(obj, value)
965
965
966
966
967 class Enum(TraitType):
967 class Enum(TraitType):
968 """An enum that whose value must be in a given sequence."""
968 """An enum that whose value must be in a given sequence."""
969
969
970 def __init__(self, values, default_value=None, allow_none=True, **metadata):
970 def __init__(self, values, default_value=None, allow_none=True, **metadata):
971 self.values = values
971 self.values = values
972 self._allow_none = allow_none
972 self._allow_none = allow_none
973 super(Enum, self).__init__(default_value, **metadata)
973 super(Enum, self).__init__(default_value, **metadata)
974
974
975 def validate(self, obj, value):
975 def validate(self, obj, value):
976 if value is None:
976 if value is None:
977 if self._allow_none:
977 if self._allow_none:
978 return value
978 return value
979
979
980 if value in self.values:
980 if value in self.values:
981 return value
981 return value
982 self.error(obj, value)
982 self.error(obj, value)
983
983
984 def info(self):
984 def info(self):
985 """ Returns a description of the trait."""
985 """ Returns a description of the trait."""
986 result = 'any of ' + repr(self.values)
986 result = 'any of ' + repr(self.values)
987 if self._allow_none:
987 if self._allow_none:
988 return result + ' or None'
988 return result + ' or None'
989 return result
989 return result
990
990
991 class CaselessStrEnum(Enum):
991 class CaselessStrEnum(Enum):
992 """An enum of strings that are caseless in validate."""
992 """An enum of strings that are caseless in validate."""
993
993
994 def validate(self, obj, value):
994 def validate(self, obj, value):
995 if value is None:
995 if value is None:
996 if self._allow_none:
996 if self._allow_none:
997 return value
997 return value
998
998
999 if not isinstance(value, str):
999 if not isinstance(value, str):
1000 self.error(obj, value)
1000 self.error(obj, value)
1001
1001
1002 for v in self.values:
1002 for v in self.values:
1003 if v.lower() == value.lower():
1003 if v.lower() == value.lower():
1004 return v
1004 return v
1005 self.error(obj, value)
1005 self.error(obj, value)
1006
1006
1007
1007
1008 class List(Instance):
1008 class List(Instance):
1009 """An instance of a Python list."""
1009 """An instance of a Python list."""
1010
1010
1011 def __init__(self, default_value=None, allow_none=True, **metadata):
1011 def __init__(self, default_value=None, allow_none=True, **metadata):
1012 """Create a list trait type from a list or tuple.
1012 """Create a list trait type from a list or tuple.
1013
1013
1014 The default value is created by doing ``list(default_value)``,
1014 The default value is created by doing ``list(default_value)``,
1015 which creates a copy of the ``default_value``.
1015 which creates a copy of the ``default_value``.
1016 """
1016 """
1017 if default_value is None:
1017 if default_value is None:
1018 args = ((),)
1018 args = ((),)
1019 elif isinstance(default_value, SequenceTypes):
1019 elif isinstance(default_value, SequenceTypes):
1020 args = (default_value,)
1020 args = (default_value,)
1021 else:
1021 else:
1022 raise TypeError('default value of List was %s' % default_value)
1022 raise TypeError('default value of List was %s' % default_value)
1023
1023
1024 super(List,self).__init__(klass=list, args=args,
1024 super(List,self).__init__(klass=list, args=args,
1025 allow_none=allow_none, **metadata)
1025 allow_none=allow_none, **metadata)
1026
1027
1028 class Dict(Instance):
1029 """An instance of a Python dict."""
1030
1031 def __init__(self, default_value=None, allow_none=True, **metadata):
1032 """Create a dict trait type from a dict.
1033
1034 The default value is created by doing ``dict(default_value)``,
1035 which creates a copy of the ``default_value``.
1036 """
1037 if default_value is None:
1038 args = ((),)
1039 elif isinstance(default_value, dict):
1040 args = (default_value,)
1041 elif isinstance(default_value, SequenceTypes):
1042 args = (default_value,)
1043 else:
1044 raise TypeError('default value of Dict was %s' % default_value)
1045
1046 super(Dict,self).__init__(klass=dict, args=args,
1047 allow_none=allow_none, **metadata)
General Comments 0
You need to be logged in to leave comments. Login now