##// END OF EJS Templates
Ongoing work on the config system....
Brian Granger -
Show More
@@ -0,0 +1,55 b''
1 import sys
2
3 from IPython.config.configurable import Configurable
4 from IPython.utils.traitlets import (
5 Bool, Unicode, Int, Float, List
6 )
7 from IPython.config.loader import KeyValueConfigLoader
8
9 class Foo(Configurable):
10
11 i = Int(0, config=True, shortname='i', help="The integer i.")
12 j = Int(1, config=True, shortname='j', help="The integer j.")
13 name = Unicode(u'Brian', config=True, shortname='name', help="First name.")
14
15
16 class Bar(Configurable):
17
18 enabled = Bool(True, config=True, shortname="bar-enabled", help="Enable bar.")
19
20
21 class MyApp(Configurable):
22
23 app_name = Unicode(u'myapp', config=True, shortname="myapp", help="The app name.")
24 running = Bool(False, config=True, shortname="running", help="Is the app running?")
25 classes = List([Bar, Foo])
26
27 def __init__(self, **kwargs):
28 Configurable.__init__(self, **kwargs)
29 self.classes.insert(0, self.__class__)
30
31 def print_help(self):
32 for cls in self.classes:
33 cls.class_print_help()
34 print
35
36 def parse_command_line(self, argv=None):
37 if argv is None:
38 argv = sys.argv[1:]
39 if '-h' in argv or '--h' in argv:
40 self.print_help()
41 sys.exit(1)
42 loader = KeyValueConfigLoader(argv=argv, classes=self.classes)
43 config = loader.load_config()
44 self.config = config
45
46
47 def main():
48 app = MyApp()
49 app.parse_command_line()
50 print "app.config:"
51 print app.config
52
53
54 if __name__ == "__main__":
55 main()
@@ -1,139 +1,170 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A base class for objects that are configurable.
4 A base class for objects that are configurable.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2010 The IPython Development Team
13 # Copyright (C) 2008-2010 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 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
26
26
27 from IPython.utils.importstring import import_item
27 from IPython.utils.importstring import import_item
28 from loader import Config
28 from loader import Config
29 from IPython.utils.traitlets import HasTraits, Instance
29 from IPython.utils.traitlets import HasTraits, Instance
30 from IPython.utils.text import indent
30
31
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Helper classes for Configurables
34 # Helper classes for Configurables
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35
36
36
37
37 class ConfigurableError(Exception):
38 class ConfigurableError(Exception):
38 pass
39 pass
39
40
40
41
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 # Configurable implementation
43 # Configurable implementation
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44
45
45
46
46 class Configurable(HasTraits):
47 class Configurable(HasTraits):
47
48
48 config = Instance(Config,(),{})
49 config = Instance(Config,(),{})
49 created = None
50 created = None
50
51
51 def __init__(self, **kwargs):
52 def __init__(self, **kwargs):
52 """Create a conigurable given a config config.
53 """Create a conigurable given a config config.
53
54
54 Parameters
55 Parameters
55 ----------
56 ----------
56 config : Config
57 config : Config
57 If this is empty, default values are used. If config is a
58 If this is empty, default values are used. If config is a
58 :class:`Config` instance, it will be used to configure the
59 :class:`Config` instance, it will be used to configure the
59 instance.
60 instance.
60
61
61 Notes
62 Notes
62 -----
63 -----
63 Subclasses of Configurable must call the :meth:`__init__` method of
64 Subclasses of Configurable must call the :meth:`__init__` method of
64 :class:`Configurable` *before* doing anything else and using
65 :class:`Configurable` *before* doing anything else and using
65 :func:`super`::
66 :func:`super`::
66
67
67 class MyConfigurable(Configurable):
68 class MyConfigurable(Configurable):
68 def __init__(self, config=None):
69 def __init__(self, config=None):
69 super(MyConfigurable, self).__init__(config)
70 super(MyConfigurable, self).__init__(config)
70 # Then any other code you need to finish initialization.
71 # Then any other code you need to finish initialization.
71
72
72 This ensures that instances will be configured properly.
73 This ensures that instances will be configured properly.
73 """
74 """
74 config = kwargs.pop('config', None)
75 config = kwargs.pop('config', None)
75 if config is not None:
76 if config is not None:
76 # We used to deepcopy, but for now we are trying to just save
77 # We used to deepcopy, but for now we are trying to just save
77 # by reference. This *could* have side effects as all components
78 # by reference. This *could* have side effects as all components
78 # will share config. In fact, I did find such a side effect in
79 # will share config. In fact, I did find such a side effect in
79 # _config_changed below. If a config attribute value was a mutable type
80 # _config_changed below. If a config attribute value was a mutable type
80 # all instances of a component were getting the same copy, effectively
81 # all instances of a component were getting the same copy, effectively
81 # making that a class attribute.
82 # making that a class attribute.
82 # self.config = deepcopy(config)
83 # self.config = deepcopy(config)
83 self.config = config
84 self.config = config
84 # This should go second so individual keyword arguments override
85 # This should go second so individual keyword arguments override
85 # the values in config.
86 # the values in config.
86 super(Configurable, self).__init__(**kwargs)
87 super(Configurable, self).__init__(**kwargs)
87 self.created = datetime.datetime.now()
88 self.created = datetime.datetime.now()
88
89
89 #-------------------------------------------------------------------------
90 #-------------------------------------------------------------------------
90 # Static trait notifiations
91 # Static trait notifiations
91 #-------------------------------------------------------------------------
92 #-------------------------------------------------------------------------
92
93
93 def _config_changed(self, name, old, new):
94 def _config_changed(self, name, old, new):
94 """Update all the class traits having ``config=True`` as metadata.
95 """Update all the class traits having ``config=True`` as metadata.
95
96
96 For any class trait with a ``config`` metadata attribute that is
97 For any class trait with a ``config`` metadata attribute that is
97 ``True``, we update the trait with the value of the corresponding
98 ``True``, we update the trait with the value of the corresponding
98 config entry.
99 config entry.
99 """
100 """
100 # Get all traits with a config metadata entry that is True
101 # Get all traits with a config metadata entry that is True
101 traits = self.traits(config=True)
102 traits = self.traits(config=True)
102
103
103 # We auto-load config section for this class as well as any parent
104 # We auto-load config section for this class as well as any parent
104 # classes that are Configurable subclasses. This starts with Configurable
105 # classes that are Configurable subclasses. This starts with Configurable
105 # and works down the mro loading the config for each section.
106 # and works down the mro loading the config for each section.
106 section_names = [cls.__name__ for cls in \
107 section_names = [cls.__name__ for cls in \
107 reversed(self.__class__.__mro__) if
108 reversed(self.__class__.__mro__) if
108 issubclass(cls, Configurable) and issubclass(self.__class__, cls)]
109 issubclass(cls, Configurable) and issubclass(self.__class__, cls)]
109
110
110 for sname in section_names:
111 for sname in section_names:
111 # Don't do a blind getattr as that would cause the config to
112 # Don't do a blind getattr as that would cause the config to
112 # dynamically create the section with name self.__class__.__name__.
113 # dynamically create the section with name self.__class__.__name__.
113 if new._has_section(sname):
114 if new._has_section(sname):
114 my_config = new[sname]
115 my_config = new[sname]
115 for k, v in traits.iteritems():
116 for k, v in traits.iteritems():
116 # Don't allow traitlets with config=True to start with
117 # Don't allow traitlets with config=True to start with
117 # uppercase. Otherwise, they are confused with Config
118 # uppercase. Otherwise, they are confused with Config
118 # subsections. But, developers shouldn't have uppercase
119 # subsections. But, developers shouldn't have uppercase
119 # attributes anyways! (PEP 6)
120 # attributes anyways! (PEP 6)
120 if k[0].upper()==k[0] and not k.startswith('_'):
121 if k[0].upper()==k[0] and not k.startswith('_'):
121 raise ConfigurableError('Configurable traitlets with '
122 raise ConfigurableError('Configurable traitlets with '
122 'config=True must start with a lowercase so they are '
123 'config=True must start with a lowercase so they are '
123 'not confused with Config subsections: %s.%s' % \
124 'not confused with Config subsections: %s.%s' % \
124 (self.__class__.__name__, k))
125 (self.__class__.__name__, k))
125 try:
126 try:
126 # Here we grab the value from the config
127 # Here we grab the value from the config
127 # If k has the naming convention of a config
128 # If k has the naming convention of a config
128 # section, it will be auto created.
129 # section, it will be auto created.
129 config_value = my_config[k]
130 config_value = my_config[k]
130 except KeyError:
131 except KeyError:
131 pass
132 pass
132 else:
133 else:
133 # print "Setting %s.%s from %s.%s=%r" % \
134 # print "Setting %s.%s from %s.%s=%r" % \
134 # (self.__class__.__name__,k,sname,k,config_value)
135 # (self.__class__.__name__,k,sname,k,config_value)
135 # We have to do a deepcopy here if we don't deepcopy the entire
136 # We have to do a deepcopy here if we don't deepcopy the entire
136 # config object. If we don't, a mutable config_value will be
137 # config object. If we don't, a mutable config_value will be
137 # shared by all instances, effectively making it a class attribute.
138 # shared by all instances, effectively making it a class attribute.
138 setattr(self, k, deepcopy(config_value))
139 setattr(self, k, deepcopy(config_value))
139
140
141 @classmethod
142 def class_get_shortnames(cls):
143 """Return the shortname to fullname dict for config=True traits."""
144 cls_traits = cls.class_traits(config=True)
145 shortnames = {}
146 for k, v in cls_traits.items():
147 shortname = v.get_metadata('shortname')
148 if shortname is not None:
149 longname = cls.__name__ + '.' + k
150 shortnames[shortname] = longname
151 return shortnames
152
153 @classmethod
154 def class_get_help(cls):
155 cls_traits = cls.class_traits(config=True)
156 final_help = []
157 final_help.append('%s options' % cls.__name__)
158 final_help.append(len(final_help[0])*'-')
159 for k, v in cls_traits.items():
160 help = v.get_metadata('help')
161 final_help.append(k + " : " + v.__class__.__name__)
162 if help is not None:
163 final_help.append(indent(help))
164 return '\n'.join(final_help)
165
166 @classmethod
167 def class_print_help(cls):
168 print cls.class_get_help()
169
170 No newline at end of file
@@ -1,451 +1,488 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 # coding: utf-8
2 # coding: utf-8
3 """A simple configuration system.
3 """A simple configuration system.
4
4
5 Authors
5 Authors
6 -------
6 -------
7 * Brian Granger
7 * Brian Granger
8 * Fernando Perez
8 * Fernando Perez
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 import os
23 import os
24 import sys
24 import sys
25
25
26 from IPython.external import argparse
26 from IPython.external import argparse
27 from IPython.utils.path import filefind
27 from IPython.utils.path import filefind
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Exceptions
30 # Exceptions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class ConfigError(Exception):
34 class ConfigError(Exception):
35 pass
35 pass
36
36
37
37
38 class ConfigLoaderError(ConfigError):
38 class ConfigLoaderError(ConfigError):
39 pass
39 pass
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Argparse fix
42 # Argparse fix
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 # Unfortunately argparse by default prints help messages to stderr instead of
45 # Unfortunately argparse by default prints help messages to stderr instead of
46 # stdout. This makes it annoying to capture long help screens at the command
46 # stdout. This makes it annoying to capture long help screens at the command
47 # line, since one must know how to pipe stderr, which many users don't know how
47 # line, since one must know how to pipe stderr, which many users don't know how
48 # to do. So we override the print_help method with one that defaults to
48 # to do. So we override the print_help method with one that defaults to
49 # stdout and use our class instead.
49 # stdout and use our class instead.
50
50
51 class ArgumentParser(argparse.ArgumentParser):
51 class ArgumentParser(argparse.ArgumentParser):
52 """Simple argparse subclass that prints help to stdout by default."""
52 """Simple argparse subclass that prints help to stdout by default."""
53
53
54 def print_help(self, file=None):
54 def print_help(self, file=None):
55 if file is None:
55 if file is None:
56 file = sys.stdout
56 file = sys.stdout
57 return super(ArgumentParser, self).print_help(file)
57 return super(ArgumentParser, self).print_help(file)
58
58
59 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
59 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 # Config class for holding config information
62 # Config class for holding config information
63 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
64
64
65
65
66 class Config(dict):
66 class Config(dict):
67 """An attribute based dict that can do smart merges."""
67 """An attribute based dict that can do smart merges."""
68
68
69 def __init__(self, *args, **kwds):
69 def __init__(self, *args, **kwds):
70 dict.__init__(self, *args, **kwds)
70 dict.__init__(self, *args, **kwds)
71 # This sets self.__dict__ = self, but it has to be done this way
71 # This sets self.__dict__ = self, but it has to be done this way
72 # because we are also overriding __setattr__.
72 # because we are also overriding __setattr__.
73 dict.__setattr__(self, '__dict__', self)
73 dict.__setattr__(self, '__dict__', self)
74
74
75 def _merge(self, other):
75 def _merge(self, other):
76 to_update = {}
76 to_update = {}
77 for k, v in other.iteritems():
77 for k, v in other.iteritems():
78 if not self.has_key(k):
78 if not self.has_key(k):
79 to_update[k] = v
79 to_update[k] = v
80 else: # I have this key
80 else: # I have this key
81 if isinstance(v, Config):
81 if isinstance(v, Config):
82 # Recursively merge common sub Configs
82 # Recursively merge common sub Configs
83 self[k]._merge(v)
83 self[k]._merge(v)
84 else:
84 else:
85 # Plain updates for non-Configs
85 # Plain updates for non-Configs
86 to_update[k] = v
86 to_update[k] = v
87
87
88 self.update(to_update)
88 self.update(to_update)
89
89
90 def _is_section_key(self, key):
90 def _is_section_key(self, key):
91 if key[0].upper()==key[0] and not key.startswith('_'):
91 if key[0].upper()==key[0] and not key.startswith('_'):
92 return True
92 return True
93 else:
93 else:
94 return False
94 return False
95
95
96 def __contains__(self, key):
96 def __contains__(self, key):
97 if self._is_section_key(key):
97 if self._is_section_key(key):
98 return True
98 return True
99 else:
99 else:
100 return super(Config, self).__contains__(key)
100 return super(Config, self).__contains__(key)
101 # .has_key is deprecated for dictionaries.
101 # .has_key is deprecated for dictionaries.
102 has_key = __contains__
102 has_key = __contains__
103
103
104 def _has_section(self, key):
104 def _has_section(self, key):
105 if self._is_section_key(key):
105 if self._is_section_key(key):
106 if super(Config, self).__contains__(key):
106 if super(Config, self).__contains__(key):
107 return True
107 return True
108 return False
108 return False
109
109
110 def copy(self):
110 def copy(self):
111 return type(self)(dict.copy(self))
111 return type(self)(dict.copy(self))
112
112
113 def __copy__(self):
113 def __copy__(self):
114 return self.copy()
114 return self.copy()
115
115
116 def __deepcopy__(self, memo):
116 def __deepcopy__(self, memo):
117 import copy
117 import copy
118 return type(self)(copy.deepcopy(self.items()))
118 return type(self)(copy.deepcopy(self.items()))
119
119
120 def __getitem__(self, key):
120 def __getitem__(self, key):
121 # We cannot use directly self._is_section_key, because it triggers
121 # We cannot use directly self._is_section_key, because it triggers
122 # infinite recursion on top of PyPy. Instead, we manually fish the
122 # infinite recursion on top of PyPy. Instead, we manually fish the
123 # bound method.
123 # bound method.
124 is_section_key = self.__class__._is_section_key.__get__(self)
124 is_section_key = self.__class__._is_section_key.__get__(self)
125
125
126 # Because we use this for an exec namespace, we need to delegate
126 # Because we use this for an exec namespace, we need to delegate
127 # the lookup of names in __builtin__ to itself. This means
127 # the lookup of names in __builtin__ to itself. This means
128 # that you can't have section or attribute names that are
128 # that you can't have section or attribute names that are
129 # builtins.
129 # builtins.
130 try:
130 try:
131 return getattr(__builtin__, key)
131 return getattr(__builtin__, key)
132 except AttributeError:
132 except AttributeError:
133 pass
133 pass
134 if is_section_key(key):
134 if is_section_key(key):
135 try:
135 try:
136 return dict.__getitem__(self, key)
136 return dict.__getitem__(self, key)
137 except KeyError:
137 except KeyError:
138 c = Config()
138 c = Config()
139 dict.__setitem__(self, key, c)
139 dict.__setitem__(self, key, c)
140 return c
140 return c
141 else:
141 else:
142 return dict.__getitem__(self, key)
142 return dict.__getitem__(self, key)
143
143
144 def __setitem__(self, key, value):
144 def __setitem__(self, key, value):
145 # Don't allow names in __builtin__ to be modified.
145 # Don't allow names in __builtin__ to be modified.
146 if hasattr(__builtin__, key):
146 if hasattr(__builtin__, key):
147 raise ConfigError('Config variable names cannot have the same name '
147 raise ConfigError('Config variable names cannot have the same name '
148 'as a Python builtin: %s' % key)
148 'as a Python builtin: %s' % key)
149 if self._is_section_key(key):
149 if self._is_section_key(key):
150 if not isinstance(value, Config):
150 if not isinstance(value, Config):
151 raise ValueError('values whose keys begin with an uppercase '
151 raise ValueError('values whose keys begin with an uppercase '
152 'char must be Config instances: %r, %r' % (key, value))
152 'char must be Config instances: %r, %r' % (key, value))
153 else:
153 else:
154 dict.__setitem__(self, key, value)
154 dict.__setitem__(self, key, value)
155
155
156 def __getattr__(self, key):
156 def __getattr__(self, key):
157 try:
157 try:
158 return self.__getitem__(key)
158 return self.__getitem__(key)
159 except KeyError, e:
159 except KeyError, e:
160 raise AttributeError(e)
160 raise AttributeError(e)
161
161
162 def __setattr__(self, key, value):
162 def __setattr__(self, key, value):
163 try:
163 try:
164 self.__setitem__(key, value)
164 self.__setitem__(key, value)
165 except KeyError, e:
165 except KeyError, e:
166 raise AttributeError(e)
166 raise AttributeError(e)
167
167
168 def __delattr__(self, key):
168 def __delattr__(self, key):
169 try:
169 try:
170 dict.__delitem__(self, key)
170 dict.__delitem__(self, key)
171 except KeyError, e:
171 except KeyError, e:
172 raise AttributeError(e)
172 raise AttributeError(e)
173
173
174
174
175 #-----------------------------------------------------------------------------
175 #-----------------------------------------------------------------------------
176 # Config loading classes
176 # Config loading classes
177 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
178
178
179
179
180 class ConfigLoader(object):
180 class ConfigLoader(object):
181 """A object for loading configurations from just about anywhere.
181 """A object for loading configurations from just about anywhere.
182
182
183 The resulting configuration is packaged as a :class:`Struct`.
183 The resulting configuration is packaged as a :class:`Struct`.
184
184
185 Notes
185 Notes
186 -----
186 -----
187 A :class:`ConfigLoader` does one thing: load a config from a source
187 A :class:`ConfigLoader` does one thing: load a config from a source
188 (file, command line arguments) and returns the data as a :class:`Struct`.
188 (file, command line arguments) and returns the data as a :class:`Struct`.
189 There are lots of things that :class:`ConfigLoader` does not do. It does
189 There are lots of things that :class:`ConfigLoader` does not do. It does
190 not implement complex logic for finding config files. It does not handle
190 not implement complex logic for finding config files. It does not handle
191 default values or merge multiple configs. These things need to be
191 default values or merge multiple configs. These things need to be
192 handled elsewhere.
192 handled elsewhere.
193 """
193 """
194
194
195 def __init__(self):
195 def __init__(self):
196 """A base class for config loaders.
196 """A base class for config loaders.
197
197
198 Examples
198 Examples
199 --------
199 --------
200
200
201 >>> cl = ConfigLoader()
201 >>> cl = ConfigLoader()
202 >>> config = cl.load_config()
202 >>> config = cl.load_config()
203 >>> config
203 >>> config
204 {}
204 {}
205 """
205 """
206 self.clear()
206 self.clear()
207
207
208 def clear(self):
208 def clear(self):
209 self.config = Config()
209 self.config = Config()
210
210
211 def load_config(self):
211 def load_config(self):
212 """Load a config from somewhere, return a :class:`Config` instance.
212 """Load a config from somewhere, return a :class:`Config` instance.
213
213
214 Usually, this will cause self.config to be set and then returned.
214 Usually, this will cause self.config to be set and then returned.
215 However, in most cases, :meth:`ConfigLoader.clear` should be called
215 However, in most cases, :meth:`ConfigLoader.clear` should be called
216 to erase any previous state.
216 to erase any previous state.
217 """
217 """
218 self.clear()
218 self.clear()
219 return self.config
219 return self.config
220
220
221
221
222 class FileConfigLoader(ConfigLoader):
222 class FileConfigLoader(ConfigLoader):
223 """A base class for file based configurations.
223 """A base class for file based configurations.
224
224
225 As we add more file based config loaders, the common logic should go
225 As we add more file based config loaders, the common logic should go
226 here.
226 here.
227 """
227 """
228 pass
228 pass
229
229
230
230
231 class PyFileConfigLoader(FileConfigLoader):
231 class PyFileConfigLoader(FileConfigLoader):
232 """A config loader for pure python files.
232 """A config loader for pure python files.
233
233
234 This calls execfile on a plain python file and looks for attributes
234 This calls execfile on a plain python file and looks for attributes
235 that are all caps. These attribute are added to the config Struct.
235 that are all caps. These attribute are added to the config Struct.
236 """
236 """
237
237
238 def __init__(self, filename, path=None):
238 def __init__(self, filename, path=None):
239 """Build a config loader for a filename and path.
239 """Build a config loader for a filename and path.
240
240
241 Parameters
241 Parameters
242 ----------
242 ----------
243 filename : str
243 filename : str
244 The file name of the config file.
244 The file name of the config file.
245 path : str, list, tuple
245 path : str, list, tuple
246 The path to search for the config file on, or a sequence of
246 The path to search for the config file on, or a sequence of
247 paths to try in order.
247 paths to try in order.
248 """
248 """
249 super(PyFileConfigLoader, self).__init__()
249 super(PyFileConfigLoader, self).__init__()
250 self.filename = filename
250 self.filename = filename
251 self.path = path
251 self.path = path
252 self.full_filename = ''
252 self.full_filename = ''
253 self.data = None
253 self.data = None
254
254
255 def load_config(self):
255 def load_config(self):
256 """Load the config from a file and return it as a Struct."""
256 """Load the config from a file and return it as a Struct."""
257 self.clear()
257 self.clear()
258 self._find_file()
258 self._find_file()
259 self._read_file_as_dict()
259 self._read_file_as_dict()
260 self._convert_to_config()
260 self._convert_to_config()
261 return self.config
261 return self.config
262
262
263 def _find_file(self):
263 def _find_file(self):
264 """Try to find the file by searching the paths."""
264 """Try to find the file by searching the paths."""
265 self.full_filename = filefind(self.filename, self.path)
265 self.full_filename = filefind(self.filename, self.path)
266
266
267 def _read_file_as_dict(self):
267 def _read_file_as_dict(self):
268 """Load the config file into self.config, with recursive loading."""
268 """Load the config file into self.config, with recursive loading."""
269 # This closure is made available in the namespace that is used
269 # This closure is made available in the namespace that is used
270 # to exec the config file. This allows users to call
270 # to exec the config file. This allows users to call
271 # load_subconfig('myconfig.py') to load config files recursively.
271 # load_subconfig('myconfig.py') to load config files recursively.
272 # It needs to be a closure because it has references to self.path
272 # It needs to be a closure because it has references to self.path
273 # and self.config. The sub-config is loaded with the same path
273 # and self.config. The sub-config is loaded with the same path
274 # as the parent, but it uses an empty config which is then merged
274 # as the parent, but it uses an empty config which is then merged
275 # with the parents.
275 # with the parents.
276 def load_subconfig(fname):
276 def load_subconfig(fname):
277 loader = PyFileConfigLoader(fname, self.path)
277 loader = PyFileConfigLoader(fname, self.path)
278 try:
278 try:
279 sub_config = loader.load_config()
279 sub_config = loader.load_config()
280 except IOError:
280 except IOError:
281 # Pass silently if the sub config is not there. This happens
281 # Pass silently if the sub config is not there. This happens
282 # when a user us using a profile, but not the default config.
282 # when a user us using a profile, but not the default config.
283 pass
283 pass
284 else:
284 else:
285 self.config._merge(sub_config)
285 self.config._merge(sub_config)
286
286
287 # Again, this needs to be a closure and should be used in config
287 # Again, this needs to be a closure and should be used in config
288 # files to get the config being loaded.
288 # files to get the config being loaded.
289 def get_config():
289 def get_config():
290 return self.config
290 return self.config
291
291
292 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
292 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
293 fs_encoding = sys.getfilesystemencoding() or 'ascii'
293 fs_encoding = sys.getfilesystemencoding() or 'ascii'
294 conf_filename = self.full_filename.encode(fs_encoding)
294 conf_filename = self.full_filename.encode(fs_encoding)
295 execfile(conf_filename, namespace)
295 execfile(conf_filename, namespace)
296
296
297 def _convert_to_config(self):
297 def _convert_to_config(self):
298 if self.data is None:
298 if self.data is None:
299 ConfigLoaderError('self.data does not exist')
299 ConfigLoaderError('self.data does not exist')
300
300
301
301
302 class CommandLineConfigLoader(ConfigLoader):
302 class CommandLineConfigLoader(ConfigLoader):
303 """A config loader for command line arguments.
303 """A config loader for command line arguments.
304
304
305 As we add more command line based loaders, the common logic should go
305 As we add more command line based loaders, the common logic should go
306 here.
306 here.
307 """
307 """
308
308
309
309
310 class KeyValueConfigLoader(CommandLineConfigLoader):
310 class KeyValueConfigLoader(CommandLineConfigLoader):
311 """A config loader that loads key value pairs from the command line.
311 """A config loader that loads key value pairs from the command line.
312
312
313 This allows command line options to be gives in the following form::
313 This allows command line options to be gives in the following form::
314
314
315 ipython Global.profile="foo" InteractiveShell.autocall=False
315 ipython Global.profile="foo" InteractiveShell.autocall=False
316 """
316 """
317
317
318 def __init__(self, argv=None):
318 def __init__(self, argv=None, classes=None):
319 """Create a key value pair config loader.
319 """Create a key value pair config loader.
320
320
321 Parameters
321 Parameters
322 ----------
322 ----------
323 argv : list
323 argv : list
324 A list that has the form of sys.argv[1:] which has unicode
324 A list that has the form of sys.argv[1:] which has unicode
325 elements of the form u"key=value". If this is None (default),
325 elements of the form u"key=value". If this is None (default),
326 then sys.argv[1:] will be used.
326 then sys.argv[1:] will be used.
327 class : (list, tuple) of Configurables
328 A sequence of Configurable classes that will be used to map
329 shortnames to longnames.
327
330
328 Returns
331 Returns
329 -------
332 -------
330 config : Config
333 config : Config
331 The resulting Config object.
334 The resulting Config object.
332
335
333 Examples
336 Examples
334 --------
337 --------
335
338
336 >>> from IPython.config.loader import KeyValueConfigLoader
339 >>> from IPython.config.loader import KeyValueConfigLoader
337 >>> cl = KeyValueConfigLoader()
340 >>> cl = KeyValueConfigLoader()
338 >>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
341 >>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
339 {'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
342 {'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
340 """
343 """
341 if argv == None:
344 if argv is None:
342 argv = sys.argv[1:]
345 argv = sys.argv[1:]
346 if classes is None:
347 classes = ()
343 self.argv = argv
348 self.argv = argv
349 self.classes = classes
344
350
345 def load_config(self, argv=None):
351 def load_config(self, argv=None, classes=None):
346 """Parse the configuration and generate the Config object.
352 """Parse the configuration and generate the Config object.
347
353
348 Parameters
354 Parameters
349 ----------
355 ----------
350 argv : list, optional
356 argv : list, optional
351 A list that has the form of sys.argv[1:] which has unicode
357 A list that has the form of sys.argv[1:] which has unicode
352 elements of the form u"key=value". If this is None (default),
358 elements of the form u"key=value". If this is None (default),
353 then self.argv will be used.
359 then self.argv will be used.
360 class : (list, tuple) of Configurables
361 A sequence of Configurable classes that will be used to map
362 shortnames to longnames.
354 """
363 """
355 self.clear()
364 self.clear()
356 if argv is None:
365 if argv is None:
357 argv = self.argv
366 argv = self.argv
367 if classes is None:
368 classes = self.classes
369
370 # print argv
371
372 shortnames = {}
373 for cls in classes:
374 sn = cls.class_get_shortnames()
375 # Check for duplicate shortnames and raise if found.
376 for k, v in sn.items():
377 if k in shortnames:
378 raise KeyError(
379 "duplicate shortname: %s and %s both use the shortname: %s" %\
380 (v, shortnames[k], k)
381 )
382 shortnames.update(sn)
383
384 # print shortnames
385
358 for item in argv:
386 for item in argv:
359 pair = tuple(item.split("="))
387 pair = tuple(item.split("="))
360 if len(pair) == 2:
388 if len(pair) == 2:
361 exec_str = 'self.config.' + pair[0] + '=' + pair[1]
389 lhs = pair[0]
362 exec exec_str in locals(), globals()
390 rhs = pair[1]
391 # Substitute longnames for shortnames.
392 if lhs in shortnames:
393 lhs = shortnames[lhs]
394 exec_str = 'self.config.' + lhs + '=' + rhs
395 try:
396 exec exec_str in locals(), globals()
397 except (NameError, SyntaxError):
398 exec_str = 'self.config.' + lhs + '="' + rhs + '"'
399 exec exec_str in locals(), globals()
363 return self.config
400 return self.config
364
401
365
402
366 class ArgParseConfigLoader(CommandLineConfigLoader):
403 class ArgParseConfigLoader(CommandLineConfigLoader):
367 """A loader that uses the argparse module to load from the command line."""
404 """A loader that uses the argparse module to load from the command line."""
368
405
369 def __init__(self, argv=None, *parser_args, **parser_kw):
406 def __init__(self, argv=None, *parser_args, **parser_kw):
370 """Create a config loader for use with argparse.
407 """Create a config loader for use with argparse.
371
408
372 Parameters
409 Parameters
373 ----------
410 ----------
374
411
375 argv : optional, list
412 argv : optional, list
376 If given, used to read command-line arguments from, otherwise
413 If given, used to read command-line arguments from, otherwise
377 sys.argv[1:] is used.
414 sys.argv[1:] is used.
378
415
379 parser_args : tuple
416 parser_args : tuple
380 A tuple of positional arguments that will be passed to the
417 A tuple of positional arguments that will be passed to the
381 constructor of :class:`argparse.ArgumentParser`.
418 constructor of :class:`argparse.ArgumentParser`.
382
419
383 parser_kw : dict
420 parser_kw : dict
384 A tuple of keyword arguments that will be passed to the
421 A tuple of keyword arguments that will be passed to the
385 constructor of :class:`argparse.ArgumentParser`.
422 constructor of :class:`argparse.ArgumentParser`.
386
423
387 Returns
424 Returns
388 -------
425 -------
389 config : Config
426 config : Config
390 The resulting Config object.
427 The resulting Config object.
391 """
428 """
392 super(CommandLineConfigLoader, self).__init__()
429 super(CommandLineConfigLoader, self).__init__()
393 if argv == None:
430 if argv == None:
394 argv = sys.argv[1:]
431 argv = sys.argv[1:]
395 self.argv = argv
432 self.argv = argv
396 self.parser_args = parser_args
433 self.parser_args = parser_args
397 self.version = parser_kw.pop("version", None)
434 self.version = parser_kw.pop("version", None)
398 kwargs = dict(argument_default=argparse.SUPPRESS)
435 kwargs = dict(argument_default=argparse.SUPPRESS)
399 kwargs.update(parser_kw)
436 kwargs.update(parser_kw)
400 self.parser_kw = kwargs
437 self.parser_kw = kwargs
401
438
402 def load_config(self, argv=None):
439 def load_config(self, argv=None):
403 """Parse command line arguments and return as a Config object.
440 """Parse command line arguments and return as a Config object.
404
441
405 Parameters
442 Parameters
406 ----------
443 ----------
407
444
408 args : optional, list
445 args : optional, list
409 If given, a list with the structure of sys.argv[1:] to parse
446 If given, a list with the structure of sys.argv[1:] to parse
410 arguments from. If not given, the instance's self.argv attribute
447 arguments from. If not given, the instance's self.argv attribute
411 (given at construction time) is used."""
448 (given at construction time) is used."""
412 self.clear()
449 self.clear()
413 if argv is None:
450 if argv is None:
414 argv = self.argv
451 argv = self.argv
415 self._create_parser()
452 self._create_parser()
416 self._parse_args(argv)
453 self._parse_args(argv)
417 self._convert_to_config()
454 self._convert_to_config()
418 return self.config
455 return self.config
419
456
420 def get_extra_args(self):
457 def get_extra_args(self):
421 if hasattr(self, 'extra_args'):
458 if hasattr(self, 'extra_args'):
422 return self.extra_args
459 return self.extra_args
423 else:
460 else:
424 return []
461 return []
425
462
426 def _create_parser(self):
463 def _create_parser(self):
427 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
464 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
428 self._add_arguments()
465 self._add_arguments()
429
466
430 def _add_arguments(self):
467 def _add_arguments(self):
431 raise NotImplementedError("subclasses must implement _add_arguments")
468 raise NotImplementedError("subclasses must implement _add_arguments")
432
469
433 def _parse_args(self, args):
470 def _parse_args(self, args):
434 """self.parser->self.parsed_data"""
471 """self.parser->self.parsed_data"""
435 # decode sys.argv to support unicode command-line options
472 # decode sys.argv to support unicode command-line options
436 uargs = []
473 uargs = []
437 for a in args:
474 for a in args:
438 if isinstance(a, str):
475 if isinstance(a, str):
439 # don't decode if we already got unicode
476 # don't decode if we already got unicode
440 a = a.decode(sys.stdin.encoding or
477 a = a.decode(sys.stdin.encoding or
441 sys.getdefaultencoding())
478 sys.getdefaultencoding())
442 uargs.append(a)
479 uargs.append(a)
443 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
480 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
444
481
445 def _convert_to_config(self):
482 def _convert_to_config(self):
446 """self.parsed_data->self.config"""
483 """self.parsed_data->self.config"""
447 for k, v in vars(self.parsed_data).iteritems():
484 for k, v in vars(self.parsed_data).iteritems():
448 exec_str = 'self.config.' + k + '= v'
485 exec_str = 'self.config.' + k + '= v'
449 exec exec_str in locals(), globals()
486 exec exec_str in locals(), globals()
450
487
451
488
@@ -1,2452 +1,2493 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-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import TryNext, UsageError
48 from IPython.core.error import TryNext, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import IPythonInputSplitter
53 from IPython.core.inputsplitter import IPythonInputSplitter
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.magic import Magic
56 from IPython.core.magic import Magic
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.plugin import PluginManager
58 from IPython.core.plugin import PluginManager
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.external.Itpl import ItplNS
60 from IPython.external.Itpl import ItplNS
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils.doctestreload import doctest_reload
63 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.io import ask_yes_no, rprint
64 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.ipstruct import Struct
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.strdispatch import StrDispatch
69 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.syspathcontext import prepended_to_syspath
70 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 List, Unicode, Instance, Type)
73 List, Unicode, Instance, Type)
74 from IPython.utils.warn import warn, error, fatal
74 from IPython.utils.warn import warn, error, fatal
75 import IPython.core.hooks
75 import IPython.core.hooks
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Globals
78 # Globals
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # compiled regexps for autoindent management
81 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Utilities
85 # Utilities
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 # store the builtin raw_input globally, and use this always, in case user code
88 # store the builtin raw_input globally, and use this always, in case user code
89 # overwrites it (like wx.py.PyShell does)
89 # overwrites it (like wx.py.PyShell does)
90 raw_input_original = raw_input
90 raw_input_original = raw_input
91
91
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107
107
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 class SpaceInInput(Exception): pass
110 class SpaceInInput(Exception): pass
111
111
112 class Bunch: pass
112 class Bunch: pass
113
113
114
114
115 def get_default_colors():
115 def get_default_colors():
116 if sys.platform=='darwin':
116 if sys.platform=='darwin':
117 return "LightBG"
117 return "LightBG"
118 elif os.name=='nt':
118 elif os.name=='nt':
119 return 'Linux'
119 return 'Linux'
120 else:
120 else:
121 return 'Linux'
121 return 'Linux'
122
122
123
123
124 class SeparateStr(Str):
124 class SeparateStr(Str):
125 """A Str subclass to validate separate_in, separate_out, etc.
125 """A Str subclass to validate separate_in, separate_out, etc.
126
126
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 """
128 """
129
129
130 def validate(self, obj, value):
130 def validate(self, obj, value):
131 if value == '0': value = ''
131 if value == '0': value = ''
132 value = value.replace('\\n','\n')
132 value = value.replace('\\n','\n')
133 return super(SeparateStr, self).validate(obj, value)
133 return super(SeparateStr, self).validate(obj, value)
134
134
135 class MultipleInstanceError(Exception):
135 class MultipleInstanceError(Exception):
136 pass
136 pass
137
137
138 class ReadlineNoRecord(object):
138 class ReadlineNoRecord(object):
139 """Context manager to execute some code, then reload readline history
139 """Context manager to execute some code, then reload readline history
140 so that interactive input to the code doesn't appear when pressing up."""
140 so that interactive input to the code doesn't appear when pressing up."""
141 def __init__(self, shell):
141 def __init__(self, shell):
142 self.shell = shell
142 self.shell = shell
143 self._nested_level = 0
143 self._nested_level = 0
144
144
145 def __enter__(self):
145 def __enter__(self):
146 if self._nested_level == 0:
146 if self._nested_level == 0:
147 try:
147 try:
148 self.orig_length = self.current_length()
148 self.orig_length = self.current_length()
149 self.readline_tail = self.get_readline_tail()
149 self.readline_tail = self.get_readline_tail()
150 except (AttributeError, IndexError): # Can fail with pyreadline
150 except (AttributeError, IndexError): # Can fail with pyreadline
151 self.orig_length, self.readline_tail = 999999, []
151 self.orig_length, self.readline_tail = 999999, []
152 self._nested_level += 1
152 self._nested_level += 1
153
153
154 def __exit__(self, type, value, traceback):
154 def __exit__(self, type, value, traceback):
155 self._nested_level -= 1
155 self._nested_level -= 1
156 if self._nested_level == 0:
156 if self._nested_level == 0:
157 # Try clipping the end if it's got longer
157 # Try clipping the end if it's got longer
158 try:
158 try:
159 e = self.current_length() - self.orig_length
159 e = self.current_length() - self.orig_length
160 if e > 0:
160 if e > 0:
161 for _ in range(e):
161 for _ in range(e):
162 self.shell.readline.remove_history_item(self.orig_length)
162 self.shell.readline.remove_history_item(self.orig_length)
163
163
164 # If it still doesn't match, just reload readline history.
164 # If it still doesn't match, just reload readline history.
165 if self.current_length() != self.orig_length \
165 if self.current_length() != self.orig_length \
166 or self.get_readline_tail() != self.readline_tail:
166 or self.get_readline_tail() != self.readline_tail:
167 self.shell.refill_readline_hist()
167 self.shell.refill_readline_hist()
168 except (AttributeError, IndexError):
168 except (AttributeError, IndexError):
169 pass
169 pass
170 # Returning False will cause exceptions to propagate
170 # Returning False will cause exceptions to propagate
171 return False
171 return False
172
172
173 def current_length(self):
173 def current_length(self):
174 return self.shell.readline.get_current_history_length()
174 return self.shell.readline.get_current_history_length()
175
175
176 def get_readline_tail(self, n=10):
176 def get_readline_tail(self, n=10):
177 """Get the last n items in readline history."""
177 """Get the last n items in readline history."""
178 end = self.shell.readline.get_current_history_length() + 1
178 end = self.shell.readline.get_current_history_length() + 1
179 start = max(end-n, 1)
179 start = max(end-n, 1)
180 ghi = self.shell.readline.get_history_item
180 ghi = self.shell.readline.get_history_item
181 return [ghi(x) for x in range(start, end)]
181 return [ghi(x) for x in range(start, end)]
182
182
183
183
184 _autocall_help = """
184 _autocall_help = """
185 Make IPython automatically call any callable object even if
185 Make IPython automatically call any callable object even if
186 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
186 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
187 automatically. The value can be '0' to disable the feature, '1' for 'smart'
187 automatically. The value can be '0' to disable the feature, '1' for 'smart'
188 autocall, where it is not applied if there are no more arguments on the line,
188 autocall, where it is not applied if there are no more arguments on the line,
189 and '2' for 'full' autocall, where all callable objects are automatically
189 and '2' for 'full' autocall, where all callable objects are automatically
190 called (even if no arguments are present). The default is '1'.
190 called (even if no arguments are present). The default is '1'.
191 """
191 """
192
192
193 #-----------------------------------------------------------------------------
193 #-----------------------------------------------------------------------------
194 # Main IPython class
194 # Main IPython class
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196
196
197 class InteractiveShell(Configurable, Magic):
197 class InteractiveShell(Configurable, Magic):
198 """An enhanced, interactive shell for Python."""
198 """An enhanced, interactive shell for Python."""
199
199
200 _instance = None
200 _instance = None
201
201
202 autocall = Enum((0,1,2), default_value=1, config=True, help=
202 autocall = Enum((0,1,2), default_value=1, config=True, help=
203 """
203 """
204 Make IPython automatically call any callable object even if you didn't
204 Make IPython automatically call any callable object even if you didn't
205 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
205 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
206 automatically. The value can be '0' to disable the feature, '1' for
206 automatically. The value can be '0' to disable the feature, '1' for
207 'smart' autocall, where it is not applied if there are no more
207 'smart' autocall, where it is not applied if there are no more
208 arguments on the line, and '2' for 'full' autocall, where all callable
208 arguments on the line, and '2' for 'full' autocall, where all callable
209 objects are automatically called (even if no arguments are present).
209 objects are automatically called (even if no arguments are present).
210 The default is '1'.
210 The default is '1'.
211 """
211 """
212 )
212 )
213 # TODO: remove all autoindent logic and put into frontends.
213 # TODO: remove all autoindent logic and put into frontends.
214 # We can't do this yet because even runlines uses the autoindent.
214 # We can't do this yet because even runlines uses the autoindent.
215 autoindent = CBool(True, config=True, help=
215 autoindent = CBool(True, config=True, help=
216 """
216 """
217 Should IPython indent code entered interactively.
217 Autoindent IPython code entered interactively.
218 """
218 """
219 )
219 )
220 automagic = CBool(True, config=True, help=
220 automagic = CBool(True, config=True, help=
221 """
221 """
222 Enable magic commands to be called without the leading %.
222 Enable magic commands to be called without the leading %.
223 """
223 """
224 )
224 )
225 cache_size = Int(1000, config=True)
225 cache_size = Int(1000, config=True, help=
226 color_info = CBool(True, config=True)
226 """
227 Set the size of the output cache. The default is 1000, you can
228 change it permanently in your config file. Setting it to 0 completely
229 disables the caching system, and the minimum value accepted is 20 (if
230 you provide a value less than 20, it is reset to 0 and a warning is
231 issued). This limit is defined because otherwise you'll spend more
232 time re-flushing a too small cache than working
233 """
234 )
235 color_info = CBool(True, config=True, help=
236 """
237 Use colors for displaying information about objects. Because this
238 information is passed through a pager (like 'less'), and some pagers
239 get confused with color codes, this capability can be turned off.
240 """
241 )
227 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
242 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
228 default_value=get_default_colors(), config=True)
243 default_value=get_default_colors(), config=True)
229 debug = CBool(False, config=True)
244 debug = CBool(False, config=True)
230 deep_reload = CBool(False, config=True)
245 deep_reload = CBool(False, config=True, help=
246 """
247 Enable deep (recursive) reloading by default. IPython can use the
248 deep_reload module which reloads changes in modules recursively (it
249 replaces the reload() function, so you don't need to change anything to
250 use it). deep_reload() forces a full reload of modules whose code may
251 have changed, which the default reload() function does not. When
252 deep_reload is off, IPython will use the normal reload(), but
253 deep_reload will still be available as dreload().
254 """
255 )
231 display_formatter = Instance(DisplayFormatter)
256 display_formatter = Instance(DisplayFormatter)
232 displayhook_class = Type(DisplayHook)
257 displayhook_class = Type(DisplayHook)
233 display_pub_class = Type(DisplayPublisher)
258 display_pub_class = Type(DisplayPublisher)
234
259
235 exit_now = CBool(False)
260 exit_now = CBool(False)
236 exiter = Instance(ExitAutocall)
261 exiter = Instance(ExitAutocall)
237 def _exiter_default(self):
262 def _exiter_default(self):
238 return ExitAutocall(self)
263 return ExitAutocall(self)
239 # Monotonically increasing execution counter
264 # Monotonically increasing execution counter
240 execution_count = Int(1)
265 execution_count = Int(1)
241 filename = Unicode("<ipython console>")
266 filename = Unicode("<ipython console>")
242 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
267 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
243
268
244 # Input splitter, to split entire cells of input into either individual
269 # Input splitter, to split entire cells of input into either individual
245 # interactive statements or whole blocks.
270 # interactive statements or whole blocks.
246 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
271 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
247 (), {})
272 (), {})
248 logstart = CBool(False, config=True)
273 logstart = CBool(False, config=True, help=
249 logfile = Unicode('', config=True)
274 """
250 logappend = Unicode('', config=True)
275 Start logging to the default log file.
276 """
277 )
278 logfile = Unicode('', config=True, help=
279 """
280 The name of the logfile to use.
281 """
282 )
283 logappend = Unicode('', config=True, help=
284 """
285 Start logging to the given file in append mode.
286 """
287 )
251 object_info_string_level = Enum((0,1,2), default_value=0,
288 object_info_string_level = Enum((0,1,2), default_value=0,
252 config=True)
289 config=True)
253 pdb = CBool(False, config=True)
290 pdb = CBool(False, config=True, help=
291 """
292 Automatically call the pdb debugger after every exception.
293 """
294 )
254
295
255 profile = Unicode('', config=True)
296 profile = Unicode('', config=True)
256 prompt_in1 = Str('In [\\#]: ', config=True)
297 prompt_in1 = Str('In [\\#]: ', config=True)
257 prompt_in2 = Str(' .\\D.: ', config=True)
298 prompt_in2 = Str(' .\\D.: ', config=True)
258 prompt_out = Str('Out[\\#]: ', config=True)
299 prompt_out = Str('Out[\\#]: ', config=True)
259 prompts_pad_left = CBool(True, config=True)
300 prompts_pad_left = CBool(True, config=True)
260 quiet = CBool(False, config=True)
301 quiet = CBool(False, config=True)
261
302
262 history_length = Int(10000, config=True)
303 history_length = Int(10000, config=True)
263
304
264 # The readline stuff will eventually be moved to the terminal subclass
305 # The readline stuff will eventually be moved to the terminal subclass
265 # but for now, we can't do that as readline is welded in everywhere.
306 # but for now, we can't do that as readline is welded in everywhere.
266 readline_use = CBool(True, config=True)
307 readline_use = CBool(True, config=True)
267 readline_merge_completions = CBool(True, config=True)
308 readline_merge_completions = CBool(True, config=True)
268 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
309 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
269 readline_remove_delims = Str('-/~', config=True)
310 readline_remove_delims = Str('-/~', config=True)
270 readline_parse_and_bind = List([
311 readline_parse_and_bind = List([
271 'tab: complete',
312 'tab: complete',
272 '"\C-l": clear-screen',
313 '"\C-l": clear-screen',
273 'set show-all-if-ambiguous on',
314 'set show-all-if-ambiguous on',
274 '"\C-o": tab-insert',
315 '"\C-o": tab-insert',
275 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
316 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
276 # crash IPython.
317 # crash IPython.
277 '"\M-o": "\d\d\d\d"',
318 '"\M-o": "\d\d\d\d"',
278 '"\M-I": "\d\d\d\d"',
319 '"\M-I": "\d\d\d\d"',
279 '"\C-r": reverse-search-history',
320 '"\C-r": reverse-search-history',
280 '"\C-s": forward-search-history',
321 '"\C-s": forward-search-history',
281 '"\C-p": history-search-backward',
322 '"\C-p": history-search-backward',
282 '"\C-n": history-search-forward',
323 '"\C-n": history-search-forward',
283 '"\e[A": history-search-backward',
324 '"\e[A": history-search-backward',
284 '"\e[B": history-search-forward',
325 '"\e[B": history-search-forward',
285 '"\C-k": kill-line',
326 '"\C-k": kill-line',
286 '"\C-u": unix-line-discard',
327 '"\C-u": unix-line-discard',
287 ], allow_none=False, config=True)
328 ], allow_none=False, config=True)
288
329
289 # TODO: this part of prompt management should be moved to the frontends.
330 # TODO: this part of prompt management should be moved to the frontends.
290 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
331 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
291 separate_in = SeparateStr('\n', config=True)
332 separate_in = SeparateStr('\n', config=True)
292 separate_out = SeparateStr('', config=True)
333 separate_out = SeparateStr('', config=True)
293 separate_out2 = SeparateStr('', config=True)
334 separate_out2 = SeparateStr('', config=True)
294 wildcards_case_sensitive = CBool(True, config=True)
335 wildcards_case_sensitive = CBool(True, config=True)
295 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
336 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
296 default_value='Context', config=True)
337 default_value='Context', config=True)
297
338
298 # Subcomponents of InteractiveShell
339 # Subcomponents of InteractiveShell
299 alias_manager = Instance('IPython.core.alias.AliasManager')
340 alias_manager = Instance('IPython.core.alias.AliasManager')
300 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
341 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
301 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
342 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
302 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
343 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
303 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
344 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
304 plugin_manager = Instance('IPython.core.plugin.PluginManager')
345 plugin_manager = Instance('IPython.core.plugin.PluginManager')
305 payload_manager = Instance('IPython.core.payload.PayloadManager')
346 payload_manager = Instance('IPython.core.payload.PayloadManager')
306 history_manager = Instance('IPython.core.history.HistoryManager')
347 history_manager = Instance('IPython.core.history.HistoryManager')
307
348
308 # Private interface
349 # Private interface
309 _post_execute = Instance(dict)
350 _post_execute = Instance(dict)
310
351
311 def __init__(self, config=None, ipython_dir=None,
352 def __init__(self, config=None, ipython_dir=None,
312 user_ns=None, user_global_ns=None,
353 user_ns=None, user_global_ns=None,
313 custom_exceptions=((), None)):
354 custom_exceptions=((), None)):
314
355
315 # This is where traits with a config_key argument are updated
356 # This is where traits with a config_key argument are updated
316 # from the values on config.
357 # from the values on config.
317 super(InteractiveShell, self).__init__(config=config)
358 super(InteractiveShell, self).__init__(config=config)
318
359
319 # These are relatively independent and stateless
360 # These are relatively independent and stateless
320 self.init_ipython_dir(ipython_dir)
361 self.init_ipython_dir(ipython_dir)
321 self.init_instance_attrs()
362 self.init_instance_attrs()
322 self.init_environment()
363 self.init_environment()
323
364
324 # Create namespaces (user_ns, user_global_ns, etc.)
365 # Create namespaces (user_ns, user_global_ns, etc.)
325 self.init_create_namespaces(user_ns, user_global_ns)
366 self.init_create_namespaces(user_ns, user_global_ns)
326 # This has to be done after init_create_namespaces because it uses
367 # This has to be done after init_create_namespaces because it uses
327 # something in self.user_ns, but before init_sys_modules, which
368 # something in self.user_ns, but before init_sys_modules, which
328 # is the first thing to modify sys.
369 # is the first thing to modify sys.
329 # TODO: When we override sys.stdout and sys.stderr before this class
370 # TODO: When we override sys.stdout and sys.stderr before this class
330 # is created, we are saving the overridden ones here. Not sure if this
371 # is created, we are saving the overridden ones here. Not sure if this
331 # is what we want to do.
372 # is what we want to do.
332 self.save_sys_module_state()
373 self.save_sys_module_state()
333 self.init_sys_modules()
374 self.init_sys_modules()
334
375
335 # While we're trying to have each part of the code directly access what
376 # While we're trying to have each part of the code directly access what
336 # it needs without keeping redundant references to objects, we have too
377 # it needs without keeping redundant references to objects, we have too
337 # much legacy code that expects ip.db to exist.
378 # much legacy code that expects ip.db to exist.
338 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
379 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
339
380
340 self.init_history()
381 self.init_history()
341 self.init_encoding()
382 self.init_encoding()
342 self.init_prefilter()
383 self.init_prefilter()
343
384
344 Magic.__init__(self, self)
385 Magic.__init__(self, self)
345
386
346 self.init_syntax_highlighting()
387 self.init_syntax_highlighting()
347 self.init_hooks()
388 self.init_hooks()
348 self.init_pushd_popd_magic()
389 self.init_pushd_popd_magic()
349 # self.init_traceback_handlers use to be here, but we moved it below
390 # self.init_traceback_handlers use to be here, but we moved it below
350 # because it and init_io have to come after init_readline.
391 # because it and init_io have to come after init_readline.
351 self.init_user_ns()
392 self.init_user_ns()
352 self.init_logger()
393 self.init_logger()
353 self.init_alias()
394 self.init_alias()
354 self.init_builtins()
395 self.init_builtins()
355
396
356 # pre_config_initialization
397 # pre_config_initialization
357
398
358 # The next section should contain everything that was in ipmaker.
399 # The next section should contain everything that was in ipmaker.
359 self.init_logstart()
400 self.init_logstart()
360
401
361 # The following was in post_config_initialization
402 # The following was in post_config_initialization
362 self.init_inspector()
403 self.init_inspector()
363 # init_readline() must come before init_io(), because init_io uses
404 # init_readline() must come before init_io(), because init_io uses
364 # readline related things.
405 # readline related things.
365 self.init_readline()
406 self.init_readline()
366 # init_completer must come after init_readline, because it needs to
407 # init_completer must come after init_readline, because it needs to
367 # know whether readline is present or not system-wide to configure the
408 # know whether readline is present or not system-wide to configure the
368 # completers, since the completion machinery can now operate
409 # completers, since the completion machinery can now operate
369 # independently of readline (e.g. over the network)
410 # independently of readline (e.g. over the network)
370 self.init_completer()
411 self.init_completer()
371 # TODO: init_io() needs to happen before init_traceback handlers
412 # TODO: init_io() needs to happen before init_traceback handlers
372 # because the traceback handlers hardcode the stdout/stderr streams.
413 # because the traceback handlers hardcode the stdout/stderr streams.
373 # This logic in in debugger.Pdb and should eventually be changed.
414 # This logic in in debugger.Pdb and should eventually be changed.
374 self.init_io()
415 self.init_io()
375 self.init_traceback_handlers(custom_exceptions)
416 self.init_traceback_handlers(custom_exceptions)
376 self.init_prompts()
417 self.init_prompts()
377 self.init_display_formatter()
418 self.init_display_formatter()
378 self.init_display_pub()
419 self.init_display_pub()
379 self.init_displayhook()
420 self.init_displayhook()
380 self.init_reload_doctest()
421 self.init_reload_doctest()
381 self.init_magics()
422 self.init_magics()
382 self.init_pdb()
423 self.init_pdb()
383 self.init_extension_manager()
424 self.init_extension_manager()
384 self.init_plugin_manager()
425 self.init_plugin_manager()
385 self.init_payload()
426 self.init_payload()
386 self.hooks.late_startup_hook()
427 self.hooks.late_startup_hook()
387 atexit.register(self.atexit_operations)
428 atexit.register(self.atexit_operations)
388
429
389 @classmethod
430 @classmethod
390 def instance(cls, *args, **kwargs):
431 def instance(cls, *args, **kwargs):
391 """Returns a global InteractiveShell instance."""
432 """Returns a global InteractiveShell instance."""
392 if cls._instance is None:
433 if cls._instance is None:
393 inst = cls(*args, **kwargs)
434 inst = cls(*args, **kwargs)
394 # Now make sure that the instance will also be returned by
435 # Now make sure that the instance will also be returned by
395 # the subclasses instance attribute.
436 # the subclasses instance attribute.
396 for subclass in cls.mro():
437 for subclass in cls.mro():
397 if issubclass(cls, subclass) and \
438 if issubclass(cls, subclass) and \
398 issubclass(subclass, InteractiveShell):
439 issubclass(subclass, InteractiveShell):
399 subclass._instance = inst
440 subclass._instance = inst
400 else:
441 else:
401 break
442 break
402 if isinstance(cls._instance, cls):
443 if isinstance(cls._instance, cls):
403 return cls._instance
444 return cls._instance
404 else:
445 else:
405 raise MultipleInstanceError(
446 raise MultipleInstanceError(
406 'Multiple incompatible subclass instances of '
447 'Multiple incompatible subclass instances of '
407 'InteractiveShell are being created.'
448 'InteractiveShell are being created.'
408 )
449 )
409
450
410 @classmethod
451 @classmethod
411 def initialized(cls):
452 def initialized(cls):
412 return hasattr(cls, "_instance")
453 return hasattr(cls, "_instance")
413
454
414 def get_ipython(self):
455 def get_ipython(self):
415 """Return the currently running IPython instance."""
456 """Return the currently running IPython instance."""
416 return self
457 return self
417
458
418 #-------------------------------------------------------------------------
459 #-------------------------------------------------------------------------
419 # Trait changed handlers
460 # Trait changed handlers
420 #-------------------------------------------------------------------------
461 #-------------------------------------------------------------------------
421
462
422 def _ipython_dir_changed(self, name, new):
463 def _ipython_dir_changed(self, name, new):
423 if not os.path.isdir(new):
464 if not os.path.isdir(new):
424 os.makedirs(new, mode = 0777)
465 os.makedirs(new, mode = 0777)
425
466
426 def set_autoindent(self,value=None):
467 def set_autoindent(self,value=None):
427 """Set the autoindent flag, checking for readline support.
468 """Set the autoindent flag, checking for readline support.
428
469
429 If called with no arguments, it acts as a toggle."""
470 If called with no arguments, it acts as a toggle."""
430
471
431 if not self.has_readline:
472 if not self.has_readline:
432 if os.name == 'posix':
473 if os.name == 'posix':
433 warn("The auto-indent feature requires the readline library")
474 warn("The auto-indent feature requires the readline library")
434 self.autoindent = 0
475 self.autoindent = 0
435 return
476 return
436 if value is None:
477 if value is None:
437 self.autoindent = not self.autoindent
478 self.autoindent = not self.autoindent
438 else:
479 else:
439 self.autoindent = value
480 self.autoindent = value
440
481
441 #-------------------------------------------------------------------------
482 #-------------------------------------------------------------------------
442 # init_* methods called by __init__
483 # init_* methods called by __init__
443 #-------------------------------------------------------------------------
484 #-------------------------------------------------------------------------
444
485
445 def init_ipython_dir(self, ipython_dir):
486 def init_ipython_dir(self, ipython_dir):
446 if ipython_dir is not None:
487 if ipython_dir is not None:
447 self.ipython_dir = ipython_dir
488 self.ipython_dir = ipython_dir
448 self.config.Global.ipython_dir = self.ipython_dir
489 self.config.Global.ipython_dir = self.ipython_dir
449 return
490 return
450
491
451 if hasattr(self.config.Global, 'ipython_dir'):
492 if hasattr(self.config.Global, 'ipython_dir'):
452 self.ipython_dir = self.config.Global.ipython_dir
493 self.ipython_dir = self.config.Global.ipython_dir
453 else:
494 else:
454 self.ipython_dir = get_ipython_dir()
495 self.ipython_dir = get_ipython_dir()
455
496
456 # All children can just read this
497 # All children can just read this
457 self.config.Global.ipython_dir = self.ipython_dir
498 self.config.Global.ipython_dir = self.ipython_dir
458
499
459 def init_instance_attrs(self):
500 def init_instance_attrs(self):
460 self.more = False
501 self.more = False
461
502
462 # command compiler
503 # command compiler
463 self.compile = CachingCompiler()
504 self.compile = CachingCompiler()
464
505
465 # Make an empty namespace, which extension writers can rely on both
506 # Make an empty namespace, which extension writers can rely on both
466 # existing and NEVER being used by ipython itself. This gives them a
507 # existing and NEVER being used by ipython itself. This gives them a
467 # convenient location for storing additional information and state
508 # convenient location for storing additional information and state
468 # their extensions may require, without fear of collisions with other
509 # their extensions may require, without fear of collisions with other
469 # ipython names that may develop later.
510 # ipython names that may develop later.
470 self.meta = Struct()
511 self.meta = Struct()
471
512
472 # Temporary files used for various purposes. Deleted at exit.
513 # Temporary files used for various purposes. Deleted at exit.
473 self.tempfiles = []
514 self.tempfiles = []
474
515
475 # Keep track of readline usage (later set by init_readline)
516 # Keep track of readline usage (later set by init_readline)
476 self.has_readline = False
517 self.has_readline = False
477
518
478 # keep track of where we started running (mainly for crash post-mortem)
519 # keep track of where we started running (mainly for crash post-mortem)
479 # This is not being used anywhere currently.
520 # This is not being used anywhere currently.
480 self.starting_dir = os.getcwd()
521 self.starting_dir = os.getcwd()
481
522
482 # Indentation management
523 # Indentation management
483 self.indent_current_nsp = 0
524 self.indent_current_nsp = 0
484
525
485 # Dict to track post-execution functions that have been registered
526 # Dict to track post-execution functions that have been registered
486 self._post_execute = {}
527 self._post_execute = {}
487
528
488 def init_environment(self):
529 def init_environment(self):
489 """Any changes we need to make to the user's environment."""
530 """Any changes we need to make to the user's environment."""
490 pass
531 pass
491
532
492 def init_encoding(self):
533 def init_encoding(self):
493 # Get system encoding at startup time. Certain terminals (like Emacs
534 # Get system encoding at startup time. Certain terminals (like Emacs
494 # under Win32 have it set to None, and we need to have a known valid
535 # under Win32 have it set to None, and we need to have a known valid
495 # encoding to use in the raw_input() method
536 # encoding to use in the raw_input() method
496 try:
537 try:
497 self.stdin_encoding = sys.stdin.encoding or 'ascii'
538 self.stdin_encoding = sys.stdin.encoding or 'ascii'
498 except AttributeError:
539 except AttributeError:
499 self.stdin_encoding = 'ascii'
540 self.stdin_encoding = 'ascii'
500
541
501 def init_syntax_highlighting(self):
542 def init_syntax_highlighting(self):
502 # Python source parser/formatter for syntax highlighting
543 # Python source parser/formatter for syntax highlighting
503 pyformat = PyColorize.Parser().format
544 pyformat = PyColorize.Parser().format
504 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
545 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
505
546
506 def init_pushd_popd_magic(self):
547 def init_pushd_popd_magic(self):
507 # for pushd/popd management
548 # for pushd/popd management
508 try:
549 try:
509 self.home_dir = get_home_dir()
550 self.home_dir = get_home_dir()
510 except HomeDirError, msg:
551 except HomeDirError, msg:
511 fatal(msg)
552 fatal(msg)
512
553
513 self.dir_stack = []
554 self.dir_stack = []
514
555
515 def init_logger(self):
556 def init_logger(self):
516 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
557 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
517 logmode='rotate')
558 logmode='rotate')
518
559
519 def init_logstart(self):
560 def init_logstart(self):
520 """Initialize logging in case it was requested at the command line.
561 """Initialize logging in case it was requested at the command line.
521 """
562 """
522 if self.logappend:
563 if self.logappend:
523 self.magic_logstart(self.logappend + ' append')
564 self.magic_logstart(self.logappend + ' append')
524 elif self.logfile:
565 elif self.logfile:
525 self.magic_logstart(self.logfile)
566 self.magic_logstart(self.logfile)
526 elif self.logstart:
567 elif self.logstart:
527 self.magic_logstart()
568 self.magic_logstart()
528
569
529 def init_builtins(self):
570 def init_builtins(self):
530 self.builtin_trap = BuiltinTrap(shell=self)
571 self.builtin_trap = BuiltinTrap(shell=self)
531
572
532 def init_inspector(self):
573 def init_inspector(self):
533 # Object inspector
574 # Object inspector
534 self.inspector = oinspect.Inspector(oinspect.InspectColors,
575 self.inspector = oinspect.Inspector(oinspect.InspectColors,
535 PyColorize.ANSICodeColors,
576 PyColorize.ANSICodeColors,
536 'NoColor',
577 'NoColor',
537 self.object_info_string_level)
578 self.object_info_string_level)
538
579
539 def init_io(self):
580 def init_io(self):
540 # This will just use sys.stdout and sys.stderr. If you want to
581 # This will just use sys.stdout and sys.stderr. If you want to
541 # override sys.stdout and sys.stderr themselves, you need to do that
582 # override sys.stdout and sys.stderr themselves, you need to do that
542 # *before* instantiating this class, because Term holds onto
583 # *before* instantiating this class, because Term holds onto
543 # references to the underlying streams.
584 # references to the underlying streams.
544 if sys.platform == 'win32' and self.has_readline:
585 if sys.platform == 'win32' and self.has_readline:
545 Term = io.IOTerm(cout=self.readline._outputfile,
586 Term = io.IOTerm(cout=self.readline._outputfile,
546 cerr=self.readline._outputfile)
587 cerr=self.readline._outputfile)
547 else:
588 else:
548 Term = io.IOTerm()
589 Term = io.IOTerm()
549 io.Term = Term
590 io.Term = Term
550
591
551 def init_prompts(self):
592 def init_prompts(self):
552 # TODO: This is a pass for now because the prompts are managed inside
593 # TODO: This is a pass for now because the prompts are managed inside
553 # the DisplayHook. Once there is a separate prompt manager, this
594 # the DisplayHook. Once there is a separate prompt manager, this
554 # will initialize that object and all prompt related information.
595 # will initialize that object and all prompt related information.
555 pass
596 pass
556
597
557 def init_display_formatter(self):
598 def init_display_formatter(self):
558 self.display_formatter = DisplayFormatter(config=self.config)
599 self.display_formatter = DisplayFormatter(config=self.config)
559
600
560 def init_display_pub(self):
601 def init_display_pub(self):
561 self.display_pub = self.display_pub_class(config=self.config)
602 self.display_pub = self.display_pub_class(config=self.config)
562
603
563 def init_displayhook(self):
604 def init_displayhook(self):
564 # Initialize displayhook, set in/out prompts and printing system
605 # Initialize displayhook, set in/out prompts and printing system
565 self.displayhook = self.displayhook_class(
606 self.displayhook = self.displayhook_class(
566 config=self.config,
607 config=self.config,
567 shell=self,
608 shell=self,
568 cache_size=self.cache_size,
609 cache_size=self.cache_size,
569 input_sep = self.separate_in,
610 input_sep = self.separate_in,
570 output_sep = self.separate_out,
611 output_sep = self.separate_out,
571 output_sep2 = self.separate_out2,
612 output_sep2 = self.separate_out2,
572 ps1 = self.prompt_in1,
613 ps1 = self.prompt_in1,
573 ps2 = self.prompt_in2,
614 ps2 = self.prompt_in2,
574 ps_out = self.prompt_out,
615 ps_out = self.prompt_out,
575 pad_left = self.prompts_pad_left
616 pad_left = self.prompts_pad_left
576 )
617 )
577 # This is a context manager that installs/revmoes the displayhook at
618 # This is a context manager that installs/revmoes the displayhook at
578 # the appropriate time.
619 # the appropriate time.
579 self.display_trap = DisplayTrap(hook=self.displayhook)
620 self.display_trap = DisplayTrap(hook=self.displayhook)
580
621
581 def init_reload_doctest(self):
622 def init_reload_doctest(self):
582 # Do a proper resetting of doctest, including the necessary displayhook
623 # Do a proper resetting of doctest, including the necessary displayhook
583 # monkeypatching
624 # monkeypatching
584 try:
625 try:
585 doctest_reload()
626 doctest_reload()
586 except ImportError:
627 except ImportError:
587 warn("doctest module does not exist.")
628 warn("doctest module does not exist.")
588
629
589 #-------------------------------------------------------------------------
630 #-------------------------------------------------------------------------
590 # Things related to injections into the sys module
631 # Things related to injections into the sys module
591 #-------------------------------------------------------------------------
632 #-------------------------------------------------------------------------
592
633
593 def save_sys_module_state(self):
634 def save_sys_module_state(self):
594 """Save the state of hooks in the sys module.
635 """Save the state of hooks in the sys module.
595
636
596 This has to be called after self.user_ns is created.
637 This has to be called after self.user_ns is created.
597 """
638 """
598 self._orig_sys_module_state = {}
639 self._orig_sys_module_state = {}
599 self._orig_sys_module_state['stdin'] = sys.stdin
640 self._orig_sys_module_state['stdin'] = sys.stdin
600 self._orig_sys_module_state['stdout'] = sys.stdout
641 self._orig_sys_module_state['stdout'] = sys.stdout
601 self._orig_sys_module_state['stderr'] = sys.stderr
642 self._orig_sys_module_state['stderr'] = sys.stderr
602 self._orig_sys_module_state['excepthook'] = sys.excepthook
643 self._orig_sys_module_state['excepthook'] = sys.excepthook
603 try:
644 try:
604 self._orig_sys_modules_main_name = self.user_ns['__name__']
645 self._orig_sys_modules_main_name = self.user_ns['__name__']
605 except KeyError:
646 except KeyError:
606 pass
647 pass
607
648
608 def restore_sys_module_state(self):
649 def restore_sys_module_state(self):
609 """Restore the state of the sys module."""
650 """Restore the state of the sys module."""
610 try:
651 try:
611 for k, v in self._orig_sys_module_state.iteritems():
652 for k, v in self._orig_sys_module_state.iteritems():
612 setattr(sys, k, v)
653 setattr(sys, k, v)
613 except AttributeError:
654 except AttributeError:
614 pass
655 pass
615 # Reset what what done in self.init_sys_modules
656 # Reset what what done in self.init_sys_modules
616 try:
657 try:
617 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
658 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
618 except (AttributeError, KeyError):
659 except (AttributeError, KeyError):
619 pass
660 pass
620
661
621 #-------------------------------------------------------------------------
662 #-------------------------------------------------------------------------
622 # Things related to hooks
663 # Things related to hooks
623 #-------------------------------------------------------------------------
664 #-------------------------------------------------------------------------
624
665
625 def init_hooks(self):
666 def init_hooks(self):
626 # hooks holds pointers used for user-side customizations
667 # hooks holds pointers used for user-side customizations
627 self.hooks = Struct()
668 self.hooks = Struct()
628
669
629 self.strdispatchers = {}
670 self.strdispatchers = {}
630
671
631 # Set all default hooks, defined in the IPython.hooks module.
672 # Set all default hooks, defined in the IPython.hooks module.
632 hooks = IPython.core.hooks
673 hooks = IPython.core.hooks
633 for hook_name in hooks.__all__:
674 for hook_name in hooks.__all__:
634 # default hooks have priority 100, i.e. low; user hooks should have
675 # default hooks have priority 100, i.e. low; user hooks should have
635 # 0-100 priority
676 # 0-100 priority
636 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
677 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
637
678
638 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
679 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
639 """set_hook(name,hook) -> sets an internal IPython hook.
680 """set_hook(name,hook) -> sets an internal IPython hook.
640
681
641 IPython exposes some of its internal API as user-modifiable hooks. By
682 IPython exposes some of its internal API as user-modifiable hooks. By
642 adding your function to one of these hooks, you can modify IPython's
683 adding your function to one of these hooks, you can modify IPython's
643 behavior to call at runtime your own routines."""
684 behavior to call at runtime your own routines."""
644
685
645 # At some point in the future, this should validate the hook before it
686 # At some point in the future, this should validate the hook before it
646 # accepts it. Probably at least check that the hook takes the number
687 # accepts it. Probably at least check that the hook takes the number
647 # of args it's supposed to.
688 # of args it's supposed to.
648
689
649 f = types.MethodType(hook,self)
690 f = types.MethodType(hook,self)
650
691
651 # check if the hook is for strdispatcher first
692 # check if the hook is for strdispatcher first
652 if str_key is not None:
693 if str_key is not None:
653 sdp = self.strdispatchers.get(name, StrDispatch())
694 sdp = self.strdispatchers.get(name, StrDispatch())
654 sdp.add_s(str_key, f, priority )
695 sdp.add_s(str_key, f, priority )
655 self.strdispatchers[name] = sdp
696 self.strdispatchers[name] = sdp
656 return
697 return
657 if re_key is not None:
698 if re_key is not None:
658 sdp = self.strdispatchers.get(name, StrDispatch())
699 sdp = self.strdispatchers.get(name, StrDispatch())
659 sdp.add_re(re.compile(re_key), f, priority )
700 sdp.add_re(re.compile(re_key), f, priority )
660 self.strdispatchers[name] = sdp
701 self.strdispatchers[name] = sdp
661 return
702 return
662
703
663 dp = getattr(self.hooks, name, None)
704 dp = getattr(self.hooks, name, None)
664 if name not in IPython.core.hooks.__all__:
705 if name not in IPython.core.hooks.__all__:
665 print "Warning! Hook '%s' is not one of %s" % \
706 print "Warning! Hook '%s' is not one of %s" % \
666 (name, IPython.core.hooks.__all__ )
707 (name, IPython.core.hooks.__all__ )
667 if not dp:
708 if not dp:
668 dp = IPython.core.hooks.CommandChainDispatcher()
709 dp = IPython.core.hooks.CommandChainDispatcher()
669
710
670 try:
711 try:
671 dp.add(f,priority)
712 dp.add(f,priority)
672 except AttributeError:
713 except AttributeError:
673 # it was not commandchain, plain old func - replace
714 # it was not commandchain, plain old func - replace
674 dp = f
715 dp = f
675
716
676 setattr(self.hooks,name, dp)
717 setattr(self.hooks,name, dp)
677
718
678 def register_post_execute(self, func):
719 def register_post_execute(self, func):
679 """Register a function for calling after code execution.
720 """Register a function for calling after code execution.
680 """
721 """
681 if not callable(func):
722 if not callable(func):
682 raise ValueError('argument %s must be callable' % func)
723 raise ValueError('argument %s must be callable' % func)
683 self._post_execute[func] = True
724 self._post_execute[func] = True
684
725
685 #-------------------------------------------------------------------------
726 #-------------------------------------------------------------------------
686 # Things related to the "main" module
727 # Things related to the "main" module
687 #-------------------------------------------------------------------------
728 #-------------------------------------------------------------------------
688
729
689 def new_main_mod(self,ns=None):
730 def new_main_mod(self,ns=None):
690 """Return a new 'main' module object for user code execution.
731 """Return a new 'main' module object for user code execution.
691 """
732 """
692 main_mod = self._user_main_module
733 main_mod = self._user_main_module
693 init_fakemod_dict(main_mod,ns)
734 init_fakemod_dict(main_mod,ns)
694 return main_mod
735 return main_mod
695
736
696 def cache_main_mod(self,ns,fname):
737 def cache_main_mod(self,ns,fname):
697 """Cache a main module's namespace.
738 """Cache a main module's namespace.
698
739
699 When scripts are executed via %run, we must keep a reference to the
740 When scripts are executed via %run, we must keep a reference to the
700 namespace of their __main__ module (a FakeModule instance) around so
741 namespace of their __main__ module (a FakeModule instance) around so
701 that Python doesn't clear it, rendering objects defined therein
742 that Python doesn't clear it, rendering objects defined therein
702 useless.
743 useless.
703
744
704 This method keeps said reference in a private dict, keyed by the
745 This method keeps said reference in a private dict, keyed by the
705 absolute path of the module object (which corresponds to the script
746 absolute path of the module object (which corresponds to the script
706 path). This way, for multiple executions of the same script we only
747 path). This way, for multiple executions of the same script we only
707 keep one copy of the namespace (the last one), thus preventing memory
748 keep one copy of the namespace (the last one), thus preventing memory
708 leaks from old references while allowing the objects from the last
749 leaks from old references while allowing the objects from the last
709 execution to be accessible.
750 execution to be accessible.
710
751
711 Note: we can not allow the actual FakeModule instances to be deleted,
752 Note: we can not allow the actual FakeModule instances to be deleted,
712 because of how Python tears down modules (it hard-sets all their
753 because of how Python tears down modules (it hard-sets all their
713 references to None without regard for reference counts). This method
754 references to None without regard for reference counts). This method
714 must therefore make a *copy* of the given namespace, to allow the
755 must therefore make a *copy* of the given namespace, to allow the
715 original module's __dict__ to be cleared and reused.
756 original module's __dict__ to be cleared and reused.
716
757
717
758
718 Parameters
759 Parameters
719 ----------
760 ----------
720 ns : a namespace (a dict, typically)
761 ns : a namespace (a dict, typically)
721
762
722 fname : str
763 fname : str
723 Filename associated with the namespace.
764 Filename associated with the namespace.
724
765
725 Examples
766 Examples
726 --------
767 --------
727
768
728 In [10]: import IPython
769 In [10]: import IPython
729
770
730 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
771 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
731
772
732 In [12]: IPython.__file__ in _ip._main_ns_cache
773 In [12]: IPython.__file__ in _ip._main_ns_cache
733 Out[12]: True
774 Out[12]: True
734 """
775 """
735 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
776 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
736
777
737 def clear_main_mod_cache(self):
778 def clear_main_mod_cache(self):
738 """Clear the cache of main modules.
779 """Clear the cache of main modules.
739
780
740 Mainly for use by utilities like %reset.
781 Mainly for use by utilities like %reset.
741
782
742 Examples
783 Examples
743 --------
784 --------
744
785
745 In [15]: import IPython
786 In [15]: import IPython
746
787
747 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
788 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
748
789
749 In [17]: len(_ip._main_ns_cache) > 0
790 In [17]: len(_ip._main_ns_cache) > 0
750 Out[17]: True
791 Out[17]: True
751
792
752 In [18]: _ip.clear_main_mod_cache()
793 In [18]: _ip.clear_main_mod_cache()
753
794
754 In [19]: len(_ip._main_ns_cache) == 0
795 In [19]: len(_ip._main_ns_cache) == 0
755 Out[19]: True
796 Out[19]: True
756 """
797 """
757 self._main_ns_cache.clear()
798 self._main_ns_cache.clear()
758
799
759 #-------------------------------------------------------------------------
800 #-------------------------------------------------------------------------
760 # Things related to debugging
801 # Things related to debugging
761 #-------------------------------------------------------------------------
802 #-------------------------------------------------------------------------
762
803
763 def init_pdb(self):
804 def init_pdb(self):
764 # Set calling of pdb on exceptions
805 # Set calling of pdb on exceptions
765 # self.call_pdb is a property
806 # self.call_pdb is a property
766 self.call_pdb = self.pdb
807 self.call_pdb = self.pdb
767
808
768 def _get_call_pdb(self):
809 def _get_call_pdb(self):
769 return self._call_pdb
810 return self._call_pdb
770
811
771 def _set_call_pdb(self,val):
812 def _set_call_pdb(self,val):
772
813
773 if val not in (0,1,False,True):
814 if val not in (0,1,False,True):
774 raise ValueError,'new call_pdb value must be boolean'
815 raise ValueError,'new call_pdb value must be boolean'
775
816
776 # store value in instance
817 # store value in instance
777 self._call_pdb = val
818 self._call_pdb = val
778
819
779 # notify the actual exception handlers
820 # notify the actual exception handlers
780 self.InteractiveTB.call_pdb = val
821 self.InteractiveTB.call_pdb = val
781
822
782 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
823 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
783 'Control auto-activation of pdb at exceptions')
824 'Control auto-activation of pdb at exceptions')
784
825
785 def debugger(self,force=False):
826 def debugger(self,force=False):
786 """Call the pydb/pdb debugger.
827 """Call the pydb/pdb debugger.
787
828
788 Keywords:
829 Keywords:
789
830
790 - force(False): by default, this routine checks the instance call_pdb
831 - force(False): by default, this routine checks the instance call_pdb
791 flag and does not actually invoke the debugger if the flag is false.
832 flag and does not actually invoke the debugger if the flag is false.
792 The 'force' option forces the debugger to activate even if the flag
833 The 'force' option forces the debugger to activate even if the flag
793 is false.
834 is false.
794 """
835 """
795
836
796 if not (force or self.call_pdb):
837 if not (force or self.call_pdb):
797 return
838 return
798
839
799 if not hasattr(sys,'last_traceback'):
840 if not hasattr(sys,'last_traceback'):
800 error('No traceback has been produced, nothing to debug.')
841 error('No traceback has been produced, nothing to debug.')
801 return
842 return
802
843
803 # use pydb if available
844 # use pydb if available
804 if debugger.has_pydb:
845 if debugger.has_pydb:
805 from pydb import pm
846 from pydb import pm
806 else:
847 else:
807 # fallback to our internal debugger
848 # fallback to our internal debugger
808 pm = lambda : self.InteractiveTB.debugger(force=True)
849 pm = lambda : self.InteractiveTB.debugger(force=True)
809
850
810 with self.readline_no_record:
851 with self.readline_no_record:
811 pm()
852 pm()
812
853
813 #-------------------------------------------------------------------------
854 #-------------------------------------------------------------------------
814 # Things related to IPython's various namespaces
855 # Things related to IPython's various namespaces
815 #-------------------------------------------------------------------------
856 #-------------------------------------------------------------------------
816
857
817 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
858 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
818 # Create the namespace where the user will operate. user_ns is
859 # Create the namespace where the user will operate. user_ns is
819 # normally the only one used, and it is passed to the exec calls as
860 # normally the only one used, and it is passed to the exec calls as
820 # the locals argument. But we do carry a user_global_ns namespace
861 # the locals argument. But we do carry a user_global_ns namespace
821 # given as the exec 'globals' argument, This is useful in embedding
862 # given as the exec 'globals' argument, This is useful in embedding
822 # situations where the ipython shell opens in a context where the
863 # situations where the ipython shell opens in a context where the
823 # distinction between locals and globals is meaningful. For
864 # distinction between locals and globals is meaningful. For
824 # non-embedded contexts, it is just the same object as the user_ns dict.
865 # non-embedded contexts, it is just the same object as the user_ns dict.
825
866
826 # FIXME. For some strange reason, __builtins__ is showing up at user
867 # FIXME. For some strange reason, __builtins__ is showing up at user
827 # level as a dict instead of a module. This is a manual fix, but I
868 # level as a dict instead of a module. This is a manual fix, but I
828 # should really track down where the problem is coming from. Alex
869 # should really track down where the problem is coming from. Alex
829 # Schmolck reported this problem first.
870 # Schmolck reported this problem first.
830
871
831 # A useful post by Alex Martelli on this topic:
872 # A useful post by Alex Martelli on this topic:
832 # Re: inconsistent value from __builtins__
873 # Re: inconsistent value from __builtins__
833 # Von: Alex Martelli <aleaxit@yahoo.com>
874 # Von: Alex Martelli <aleaxit@yahoo.com>
834 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
875 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
835 # Gruppen: comp.lang.python
876 # Gruppen: comp.lang.python
836
877
837 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
878 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
838 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
879 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
839 # > <type 'dict'>
880 # > <type 'dict'>
840 # > >>> print type(__builtins__)
881 # > >>> print type(__builtins__)
841 # > <type 'module'>
882 # > <type 'module'>
842 # > Is this difference in return value intentional?
883 # > Is this difference in return value intentional?
843
884
844 # Well, it's documented that '__builtins__' can be either a dictionary
885 # Well, it's documented that '__builtins__' can be either a dictionary
845 # or a module, and it's been that way for a long time. Whether it's
886 # or a module, and it's been that way for a long time. Whether it's
846 # intentional (or sensible), I don't know. In any case, the idea is
887 # intentional (or sensible), I don't know. In any case, the idea is
847 # that if you need to access the built-in namespace directly, you
888 # that if you need to access the built-in namespace directly, you
848 # should start with "import __builtin__" (note, no 's') which will
889 # should start with "import __builtin__" (note, no 's') which will
849 # definitely give you a module. Yeah, it's somewhat confusing:-(.
890 # definitely give you a module. Yeah, it's somewhat confusing:-(.
850
891
851 # These routines return properly built dicts as needed by the rest of
892 # These routines return properly built dicts as needed by the rest of
852 # the code, and can also be used by extension writers to generate
893 # the code, and can also be used by extension writers to generate
853 # properly initialized namespaces.
894 # properly initialized namespaces.
854 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
895 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
855 user_global_ns)
896 user_global_ns)
856
897
857 # Assign namespaces
898 # Assign namespaces
858 # This is the namespace where all normal user variables live
899 # This is the namespace where all normal user variables live
859 self.user_ns = user_ns
900 self.user_ns = user_ns
860 self.user_global_ns = user_global_ns
901 self.user_global_ns = user_global_ns
861
902
862 # An auxiliary namespace that checks what parts of the user_ns were
903 # An auxiliary namespace that checks what parts of the user_ns were
863 # loaded at startup, so we can list later only variables defined in
904 # loaded at startup, so we can list later only variables defined in
864 # actual interactive use. Since it is always a subset of user_ns, it
905 # actual interactive use. Since it is always a subset of user_ns, it
865 # doesn't need to be separately tracked in the ns_table.
906 # doesn't need to be separately tracked in the ns_table.
866 self.user_ns_hidden = {}
907 self.user_ns_hidden = {}
867
908
868 # A namespace to keep track of internal data structures to prevent
909 # A namespace to keep track of internal data structures to prevent
869 # them from cluttering user-visible stuff. Will be updated later
910 # them from cluttering user-visible stuff. Will be updated later
870 self.internal_ns = {}
911 self.internal_ns = {}
871
912
872 # Now that FakeModule produces a real module, we've run into a nasty
913 # Now that FakeModule produces a real module, we've run into a nasty
873 # problem: after script execution (via %run), the module where the user
914 # problem: after script execution (via %run), the module where the user
874 # code ran is deleted. Now that this object is a true module (needed
915 # code ran is deleted. Now that this object is a true module (needed
875 # so docetst and other tools work correctly), the Python module
916 # so docetst and other tools work correctly), the Python module
876 # teardown mechanism runs over it, and sets to None every variable
917 # teardown mechanism runs over it, and sets to None every variable
877 # present in that module. Top-level references to objects from the
918 # present in that module. Top-level references to objects from the
878 # script survive, because the user_ns is updated with them. However,
919 # script survive, because the user_ns is updated with them. However,
879 # calling functions defined in the script that use other things from
920 # calling functions defined in the script that use other things from
880 # the script will fail, because the function's closure had references
921 # the script will fail, because the function's closure had references
881 # to the original objects, which are now all None. So we must protect
922 # to the original objects, which are now all None. So we must protect
882 # these modules from deletion by keeping a cache.
923 # these modules from deletion by keeping a cache.
883 #
924 #
884 # To avoid keeping stale modules around (we only need the one from the
925 # To avoid keeping stale modules around (we only need the one from the
885 # last run), we use a dict keyed with the full path to the script, so
926 # last run), we use a dict keyed with the full path to the script, so
886 # only the last version of the module is held in the cache. Note,
927 # only the last version of the module is held in the cache. Note,
887 # however, that we must cache the module *namespace contents* (their
928 # however, that we must cache the module *namespace contents* (their
888 # __dict__). Because if we try to cache the actual modules, old ones
929 # __dict__). Because if we try to cache the actual modules, old ones
889 # (uncached) could be destroyed while still holding references (such as
930 # (uncached) could be destroyed while still holding references (such as
890 # those held by GUI objects that tend to be long-lived)>
931 # those held by GUI objects that tend to be long-lived)>
891 #
932 #
892 # The %reset command will flush this cache. See the cache_main_mod()
933 # The %reset command will flush this cache. See the cache_main_mod()
893 # and clear_main_mod_cache() methods for details on use.
934 # and clear_main_mod_cache() methods for details on use.
894
935
895 # This is the cache used for 'main' namespaces
936 # This is the cache used for 'main' namespaces
896 self._main_ns_cache = {}
937 self._main_ns_cache = {}
897 # And this is the single instance of FakeModule whose __dict__ we keep
938 # And this is the single instance of FakeModule whose __dict__ we keep
898 # copying and clearing for reuse on each %run
939 # copying and clearing for reuse on each %run
899 self._user_main_module = FakeModule()
940 self._user_main_module = FakeModule()
900
941
901 # A table holding all the namespaces IPython deals with, so that
942 # A table holding all the namespaces IPython deals with, so that
902 # introspection facilities can search easily.
943 # introspection facilities can search easily.
903 self.ns_table = {'user':user_ns,
944 self.ns_table = {'user':user_ns,
904 'user_global':user_global_ns,
945 'user_global':user_global_ns,
905 'internal':self.internal_ns,
946 'internal':self.internal_ns,
906 'builtin':__builtin__.__dict__
947 'builtin':__builtin__.__dict__
907 }
948 }
908
949
909 # Similarly, track all namespaces where references can be held and that
950 # Similarly, track all namespaces where references can be held and that
910 # we can safely clear (so it can NOT include builtin). This one can be
951 # we can safely clear (so it can NOT include builtin). This one can be
911 # a simple list. Note that the main execution namespaces, user_ns and
952 # a simple list. Note that the main execution namespaces, user_ns and
912 # user_global_ns, can NOT be listed here, as clearing them blindly
953 # user_global_ns, can NOT be listed here, as clearing them blindly
913 # causes errors in object __del__ methods. Instead, the reset() method
954 # causes errors in object __del__ methods. Instead, the reset() method
914 # clears them manually and carefully.
955 # clears them manually and carefully.
915 self.ns_refs_table = [ self.user_ns_hidden,
956 self.ns_refs_table = [ self.user_ns_hidden,
916 self.internal_ns, self._main_ns_cache ]
957 self.internal_ns, self._main_ns_cache ]
917
958
918 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
959 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
919 """Return a valid local and global user interactive namespaces.
960 """Return a valid local and global user interactive namespaces.
920
961
921 This builds a dict with the minimal information needed to operate as a
962 This builds a dict with the minimal information needed to operate as a
922 valid IPython user namespace, which you can pass to the various
963 valid IPython user namespace, which you can pass to the various
923 embedding classes in ipython. The default implementation returns the
964 embedding classes in ipython. The default implementation returns the
924 same dict for both the locals and the globals to allow functions to
965 same dict for both the locals and the globals to allow functions to
925 refer to variables in the namespace. Customized implementations can
966 refer to variables in the namespace. Customized implementations can
926 return different dicts. The locals dictionary can actually be anything
967 return different dicts. The locals dictionary can actually be anything
927 following the basic mapping protocol of a dict, but the globals dict
968 following the basic mapping protocol of a dict, but the globals dict
928 must be a true dict, not even a subclass. It is recommended that any
969 must be a true dict, not even a subclass. It is recommended that any
929 custom object for the locals namespace synchronize with the globals
970 custom object for the locals namespace synchronize with the globals
930 dict somehow.
971 dict somehow.
931
972
932 Raises TypeError if the provided globals namespace is not a true dict.
973 Raises TypeError if the provided globals namespace is not a true dict.
933
974
934 Parameters
975 Parameters
935 ----------
976 ----------
936 user_ns : dict-like, optional
977 user_ns : dict-like, optional
937 The current user namespace. The items in this namespace should
978 The current user namespace. The items in this namespace should
938 be included in the output. If None, an appropriate blank
979 be included in the output. If None, an appropriate blank
939 namespace should be created.
980 namespace should be created.
940 user_global_ns : dict, optional
981 user_global_ns : dict, optional
941 The current user global namespace. The items in this namespace
982 The current user global namespace. The items in this namespace
942 should be included in the output. If None, an appropriate
983 should be included in the output. If None, an appropriate
943 blank namespace should be created.
984 blank namespace should be created.
944
985
945 Returns
986 Returns
946 -------
987 -------
947 A pair of dictionary-like object to be used as the local namespace
988 A pair of dictionary-like object to be used as the local namespace
948 of the interpreter and a dict to be used as the global namespace.
989 of the interpreter and a dict to be used as the global namespace.
949 """
990 """
950
991
951
992
952 # We must ensure that __builtin__ (without the final 's') is always
993 # We must ensure that __builtin__ (without the final 's') is always
953 # available and pointing to the __builtin__ *module*. For more details:
994 # available and pointing to the __builtin__ *module*. For more details:
954 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
995 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
955
996
956 if user_ns is None:
997 if user_ns is None:
957 # Set __name__ to __main__ to better match the behavior of the
998 # Set __name__ to __main__ to better match the behavior of the
958 # normal interpreter.
999 # normal interpreter.
959 user_ns = {'__name__' :'__main__',
1000 user_ns = {'__name__' :'__main__',
960 '__builtin__' : __builtin__,
1001 '__builtin__' : __builtin__,
961 '__builtins__' : __builtin__,
1002 '__builtins__' : __builtin__,
962 }
1003 }
963 else:
1004 else:
964 user_ns.setdefault('__name__','__main__')
1005 user_ns.setdefault('__name__','__main__')
965 user_ns.setdefault('__builtin__',__builtin__)
1006 user_ns.setdefault('__builtin__',__builtin__)
966 user_ns.setdefault('__builtins__',__builtin__)
1007 user_ns.setdefault('__builtins__',__builtin__)
967
1008
968 if user_global_ns is None:
1009 if user_global_ns is None:
969 user_global_ns = user_ns
1010 user_global_ns = user_ns
970 if type(user_global_ns) is not dict:
1011 if type(user_global_ns) is not dict:
971 raise TypeError("user_global_ns must be a true dict; got %r"
1012 raise TypeError("user_global_ns must be a true dict; got %r"
972 % type(user_global_ns))
1013 % type(user_global_ns))
973
1014
974 return user_ns, user_global_ns
1015 return user_ns, user_global_ns
975
1016
976 def init_sys_modules(self):
1017 def init_sys_modules(self):
977 # We need to insert into sys.modules something that looks like a
1018 # We need to insert into sys.modules something that looks like a
978 # module but which accesses the IPython namespace, for shelve and
1019 # module but which accesses the IPython namespace, for shelve and
979 # pickle to work interactively. Normally they rely on getting
1020 # pickle to work interactively. Normally they rely on getting
980 # everything out of __main__, but for embedding purposes each IPython
1021 # everything out of __main__, but for embedding purposes each IPython
981 # instance has its own private namespace, so we can't go shoving
1022 # instance has its own private namespace, so we can't go shoving
982 # everything into __main__.
1023 # everything into __main__.
983
1024
984 # note, however, that we should only do this for non-embedded
1025 # note, however, that we should only do this for non-embedded
985 # ipythons, which really mimic the __main__.__dict__ with their own
1026 # ipythons, which really mimic the __main__.__dict__ with their own
986 # namespace. Embedded instances, on the other hand, should not do
1027 # namespace. Embedded instances, on the other hand, should not do
987 # this because they need to manage the user local/global namespaces
1028 # this because they need to manage the user local/global namespaces
988 # only, but they live within a 'normal' __main__ (meaning, they
1029 # only, but they live within a 'normal' __main__ (meaning, they
989 # shouldn't overtake the execution environment of the script they're
1030 # shouldn't overtake the execution environment of the script they're
990 # embedded in).
1031 # embedded in).
991
1032
992 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1033 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
993
1034
994 try:
1035 try:
995 main_name = self.user_ns['__name__']
1036 main_name = self.user_ns['__name__']
996 except KeyError:
1037 except KeyError:
997 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1038 raise KeyError('user_ns dictionary MUST have a "__name__" key')
998 else:
1039 else:
999 sys.modules[main_name] = FakeModule(self.user_ns)
1040 sys.modules[main_name] = FakeModule(self.user_ns)
1000
1041
1001 def init_user_ns(self):
1042 def init_user_ns(self):
1002 """Initialize all user-visible namespaces to their minimum defaults.
1043 """Initialize all user-visible namespaces to their minimum defaults.
1003
1044
1004 Certain history lists are also initialized here, as they effectively
1045 Certain history lists are also initialized here, as they effectively
1005 act as user namespaces.
1046 act as user namespaces.
1006
1047
1007 Notes
1048 Notes
1008 -----
1049 -----
1009 All data structures here are only filled in, they are NOT reset by this
1050 All data structures here are only filled in, they are NOT reset by this
1010 method. If they were not empty before, data will simply be added to
1051 method. If they were not empty before, data will simply be added to
1011 therm.
1052 therm.
1012 """
1053 """
1013 # This function works in two parts: first we put a few things in
1054 # This function works in two parts: first we put a few things in
1014 # user_ns, and we sync that contents into user_ns_hidden so that these
1055 # user_ns, and we sync that contents into user_ns_hidden so that these
1015 # initial variables aren't shown by %who. After the sync, we add the
1056 # initial variables aren't shown by %who. After the sync, we add the
1016 # rest of what we *do* want the user to see with %who even on a new
1057 # rest of what we *do* want the user to see with %who even on a new
1017 # session (probably nothing, so theye really only see their own stuff)
1058 # session (probably nothing, so theye really only see their own stuff)
1018
1059
1019 # The user dict must *always* have a __builtin__ reference to the
1060 # The user dict must *always* have a __builtin__ reference to the
1020 # Python standard __builtin__ namespace, which must be imported.
1061 # Python standard __builtin__ namespace, which must be imported.
1021 # This is so that certain operations in prompt evaluation can be
1062 # This is so that certain operations in prompt evaluation can be
1022 # reliably executed with builtins. Note that we can NOT use
1063 # reliably executed with builtins. Note that we can NOT use
1023 # __builtins__ (note the 's'), because that can either be a dict or a
1064 # __builtins__ (note the 's'), because that can either be a dict or a
1024 # module, and can even mutate at runtime, depending on the context
1065 # module, and can even mutate at runtime, depending on the context
1025 # (Python makes no guarantees on it). In contrast, __builtin__ is
1066 # (Python makes no guarantees on it). In contrast, __builtin__ is
1026 # always a module object, though it must be explicitly imported.
1067 # always a module object, though it must be explicitly imported.
1027
1068
1028 # For more details:
1069 # For more details:
1029 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1070 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1030 ns = dict(__builtin__ = __builtin__)
1071 ns = dict(__builtin__ = __builtin__)
1031
1072
1032 # Put 'help' in the user namespace
1073 # Put 'help' in the user namespace
1033 try:
1074 try:
1034 from site import _Helper
1075 from site import _Helper
1035 ns['help'] = _Helper()
1076 ns['help'] = _Helper()
1036 except ImportError:
1077 except ImportError:
1037 warn('help() not available - check site.py')
1078 warn('help() not available - check site.py')
1038
1079
1039 # make global variables for user access to the histories
1080 # make global variables for user access to the histories
1040 ns['_ih'] = self.history_manager.input_hist_parsed
1081 ns['_ih'] = self.history_manager.input_hist_parsed
1041 ns['_oh'] = self.history_manager.output_hist
1082 ns['_oh'] = self.history_manager.output_hist
1042 ns['_dh'] = self.history_manager.dir_hist
1083 ns['_dh'] = self.history_manager.dir_hist
1043
1084
1044 ns['_sh'] = shadowns
1085 ns['_sh'] = shadowns
1045
1086
1046 # user aliases to input and output histories. These shouldn't show up
1087 # user aliases to input and output histories. These shouldn't show up
1047 # in %who, as they can have very large reprs.
1088 # in %who, as they can have very large reprs.
1048 ns['In'] = self.history_manager.input_hist_parsed
1089 ns['In'] = self.history_manager.input_hist_parsed
1049 ns['Out'] = self.history_manager.output_hist
1090 ns['Out'] = self.history_manager.output_hist
1050
1091
1051 # Store myself as the public api!!!
1092 # Store myself as the public api!!!
1052 ns['get_ipython'] = self.get_ipython
1093 ns['get_ipython'] = self.get_ipython
1053
1094
1054 ns['exit'] = self.exiter
1095 ns['exit'] = self.exiter
1055 ns['quit'] = self.exiter
1096 ns['quit'] = self.exiter
1056
1097
1057 # Sync what we've added so far to user_ns_hidden so these aren't seen
1098 # Sync what we've added so far to user_ns_hidden so these aren't seen
1058 # by %who
1099 # by %who
1059 self.user_ns_hidden.update(ns)
1100 self.user_ns_hidden.update(ns)
1060
1101
1061 # Anything put into ns now would show up in %who. Think twice before
1102 # Anything put into ns now would show up in %who. Think twice before
1062 # putting anything here, as we really want %who to show the user their
1103 # putting anything here, as we really want %who to show the user their
1063 # stuff, not our variables.
1104 # stuff, not our variables.
1064
1105
1065 # Finally, update the real user's namespace
1106 # Finally, update the real user's namespace
1066 self.user_ns.update(ns)
1107 self.user_ns.update(ns)
1067
1108
1068 def reset(self, new_session=True):
1109 def reset(self, new_session=True):
1069 """Clear all internal namespaces, and attempt to release references to
1110 """Clear all internal namespaces, and attempt to release references to
1070 user objects.
1111 user objects.
1071
1112
1072 If new_session is True, a new history session will be opened.
1113 If new_session is True, a new history session will be opened.
1073 """
1114 """
1074 # Clear histories
1115 # Clear histories
1075 self.history_manager.reset(new_session)
1116 self.history_manager.reset(new_session)
1076 # Reset counter used to index all histories
1117 # Reset counter used to index all histories
1077 if new_session:
1118 if new_session:
1078 self.execution_count = 1
1119 self.execution_count = 1
1079
1120
1080 # Flush cached output items
1121 # Flush cached output items
1081 self.displayhook.flush()
1122 self.displayhook.flush()
1082
1123
1083 # Restore the user namespaces to minimal usability
1124 # Restore the user namespaces to minimal usability
1084 for ns in self.ns_refs_table:
1125 for ns in self.ns_refs_table:
1085 ns.clear()
1126 ns.clear()
1086
1127
1087 # The main execution namespaces must be cleared very carefully,
1128 # The main execution namespaces must be cleared very carefully,
1088 # skipping the deletion of the builtin-related keys, because doing so
1129 # skipping the deletion of the builtin-related keys, because doing so
1089 # would cause errors in many object's __del__ methods.
1130 # would cause errors in many object's __del__ methods.
1090 for ns in [self.user_ns, self.user_global_ns]:
1131 for ns in [self.user_ns, self.user_global_ns]:
1091 drop_keys = set(ns.keys())
1132 drop_keys = set(ns.keys())
1092 drop_keys.discard('__builtin__')
1133 drop_keys.discard('__builtin__')
1093 drop_keys.discard('__builtins__')
1134 drop_keys.discard('__builtins__')
1094 for k in drop_keys:
1135 for k in drop_keys:
1095 del ns[k]
1136 del ns[k]
1096
1137
1097 # Restore the user namespaces to minimal usability
1138 # Restore the user namespaces to minimal usability
1098 self.init_user_ns()
1139 self.init_user_ns()
1099
1140
1100 # Restore the default and user aliases
1141 # Restore the default and user aliases
1101 self.alias_manager.clear_aliases()
1142 self.alias_manager.clear_aliases()
1102 self.alias_manager.init_aliases()
1143 self.alias_manager.init_aliases()
1103
1144
1104 # Flush the private list of module references kept for script
1145 # Flush the private list of module references kept for script
1105 # execution protection
1146 # execution protection
1106 self.clear_main_mod_cache()
1147 self.clear_main_mod_cache()
1107
1148
1108 # Clear out the namespace from the last %run
1149 # Clear out the namespace from the last %run
1109 self.new_main_mod()
1150 self.new_main_mod()
1110
1151
1111 def reset_selective(self, regex=None):
1152 def reset_selective(self, regex=None):
1112 """Clear selective variables from internal namespaces based on a
1153 """Clear selective variables from internal namespaces based on a
1113 specified regular expression.
1154 specified regular expression.
1114
1155
1115 Parameters
1156 Parameters
1116 ----------
1157 ----------
1117 regex : string or compiled pattern, optional
1158 regex : string or compiled pattern, optional
1118 A regular expression pattern that will be used in searching
1159 A regular expression pattern that will be used in searching
1119 variable names in the users namespaces.
1160 variable names in the users namespaces.
1120 """
1161 """
1121 if regex is not None:
1162 if regex is not None:
1122 try:
1163 try:
1123 m = re.compile(regex)
1164 m = re.compile(regex)
1124 except TypeError:
1165 except TypeError:
1125 raise TypeError('regex must be a string or compiled pattern')
1166 raise TypeError('regex must be a string or compiled pattern')
1126 # Search for keys in each namespace that match the given regex
1167 # Search for keys in each namespace that match the given regex
1127 # If a match is found, delete the key/value pair.
1168 # If a match is found, delete the key/value pair.
1128 for ns in self.ns_refs_table:
1169 for ns in self.ns_refs_table:
1129 for var in ns:
1170 for var in ns:
1130 if m.search(var):
1171 if m.search(var):
1131 del ns[var]
1172 del ns[var]
1132
1173
1133 def push(self, variables, interactive=True):
1174 def push(self, variables, interactive=True):
1134 """Inject a group of variables into the IPython user namespace.
1175 """Inject a group of variables into the IPython user namespace.
1135
1176
1136 Parameters
1177 Parameters
1137 ----------
1178 ----------
1138 variables : dict, str or list/tuple of str
1179 variables : dict, str or list/tuple of str
1139 The variables to inject into the user's namespace. If a dict, a
1180 The variables to inject into the user's namespace. If a dict, a
1140 simple update is done. If a str, the string is assumed to have
1181 simple update is done. If a str, the string is assumed to have
1141 variable names separated by spaces. A list/tuple of str can also
1182 variable names separated by spaces. A list/tuple of str can also
1142 be used to give the variable names. If just the variable names are
1183 be used to give the variable names. If just the variable names are
1143 give (list/tuple/str) then the variable values looked up in the
1184 give (list/tuple/str) then the variable values looked up in the
1144 callers frame.
1185 callers frame.
1145 interactive : bool
1186 interactive : bool
1146 If True (default), the variables will be listed with the ``who``
1187 If True (default), the variables will be listed with the ``who``
1147 magic.
1188 magic.
1148 """
1189 """
1149 vdict = None
1190 vdict = None
1150
1191
1151 # We need a dict of name/value pairs to do namespace updates.
1192 # We need a dict of name/value pairs to do namespace updates.
1152 if isinstance(variables, dict):
1193 if isinstance(variables, dict):
1153 vdict = variables
1194 vdict = variables
1154 elif isinstance(variables, (basestring, list, tuple)):
1195 elif isinstance(variables, (basestring, list, tuple)):
1155 if isinstance(variables, basestring):
1196 if isinstance(variables, basestring):
1156 vlist = variables.split()
1197 vlist = variables.split()
1157 else:
1198 else:
1158 vlist = variables
1199 vlist = variables
1159 vdict = {}
1200 vdict = {}
1160 cf = sys._getframe(1)
1201 cf = sys._getframe(1)
1161 for name in vlist:
1202 for name in vlist:
1162 try:
1203 try:
1163 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1204 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1164 except:
1205 except:
1165 print ('Could not get variable %s from %s' %
1206 print ('Could not get variable %s from %s' %
1166 (name,cf.f_code.co_name))
1207 (name,cf.f_code.co_name))
1167 else:
1208 else:
1168 raise ValueError('variables must be a dict/str/list/tuple')
1209 raise ValueError('variables must be a dict/str/list/tuple')
1169
1210
1170 # Propagate variables to user namespace
1211 # Propagate variables to user namespace
1171 self.user_ns.update(vdict)
1212 self.user_ns.update(vdict)
1172
1213
1173 # And configure interactive visibility
1214 # And configure interactive visibility
1174 config_ns = self.user_ns_hidden
1215 config_ns = self.user_ns_hidden
1175 if interactive:
1216 if interactive:
1176 for name, val in vdict.iteritems():
1217 for name, val in vdict.iteritems():
1177 config_ns.pop(name, None)
1218 config_ns.pop(name, None)
1178 else:
1219 else:
1179 for name,val in vdict.iteritems():
1220 for name,val in vdict.iteritems():
1180 config_ns[name] = val
1221 config_ns[name] = val
1181
1222
1182 #-------------------------------------------------------------------------
1223 #-------------------------------------------------------------------------
1183 # Things related to object introspection
1224 # Things related to object introspection
1184 #-------------------------------------------------------------------------
1225 #-------------------------------------------------------------------------
1185
1226
1186 def _ofind(self, oname, namespaces=None):
1227 def _ofind(self, oname, namespaces=None):
1187 """Find an object in the available namespaces.
1228 """Find an object in the available namespaces.
1188
1229
1189 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1230 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1190
1231
1191 Has special code to detect magic functions.
1232 Has special code to detect magic functions.
1192 """
1233 """
1193 #oname = oname.strip()
1234 #oname = oname.strip()
1194 #print '1- oname: <%r>' % oname # dbg
1235 #print '1- oname: <%r>' % oname # dbg
1195 try:
1236 try:
1196 oname = oname.strip().encode('ascii')
1237 oname = oname.strip().encode('ascii')
1197 #print '2- oname: <%r>' % oname # dbg
1238 #print '2- oname: <%r>' % oname # dbg
1198 except UnicodeEncodeError:
1239 except UnicodeEncodeError:
1199 print 'Python identifiers can only contain ascii characters.'
1240 print 'Python identifiers can only contain ascii characters.'
1200 return dict(found=False)
1241 return dict(found=False)
1201
1242
1202 alias_ns = None
1243 alias_ns = None
1203 if namespaces is None:
1244 if namespaces is None:
1204 # Namespaces to search in:
1245 # Namespaces to search in:
1205 # Put them in a list. The order is important so that we
1246 # Put them in a list. The order is important so that we
1206 # find things in the same order that Python finds them.
1247 # find things in the same order that Python finds them.
1207 namespaces = [ ('Interactive', self.user_ns),
1248 namespaces = [ ('Interactive', self.user_ns),
1208 ('IPython internal', self.internal_ns),
1249 ('IPython internal', self.internal_ns),
1209 ('Python builtin', __builtin__.__dict__),
1250 ('Python builtin', __builtin__.__dict__),
1210 ('Alias', self.alias_manager.alias_table),
1251 ('Alias', self.alias_manager.alias_table),
1211 ]
1252 ]
1212 alias_ns = self.alias_manager.alias_table
1253 alias_ns = self.alias_manager.alias_table
1213
1254
1214 # initialize results to 'null'
1255 # initialize results to 'null'
1215 found = False; obj = None; ospace = None; ds = None;
1256 found = False; obj = None; ospace = None; ds = None;
1216 ismagic = False; isalias = False; parent = None
1257 ismagic = False; isalias = False; parent = None
1217
1258
1218 # We need to special-case 'print', which as of python2.6 registers as a
1259 # We need to special-case 'print', which as of python2.6 registers as a
1219 # function but should only be treated as one if print_function was
1260 # function but should only be treated as one if print_function was
1220 # loaded with a future import. In this case, just bail.
1261 # loaded with a future import. In this case, just bail.
1221 if (oname == 'print' and not (self.compile.compiler_flags &
1262 if (oname == 'print' and not (self.compile.compiler_flags &
1222 __future__.CO_FUTURE_PRINT_FUNCTION)):
1263 __future__.CO_FUTURE_PRINT_FUNCTION)):
1223 return {'found':found, 'obj':obj, 'namespace':ospace,
1264 return {'found':found, 'obj':obj, 'namespace':ospace,
1224 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1225
1266
1226 # Look for the given name by splitting it in parts. If the head is
1267 # Look for the given name by splitting it in parts. If the head is
1227 # found, then we look for all the remaining parts as members, and only
1268 # found, then we look for all the remaining parts as members, and only
1228 # declare success if we can find them all.
1269 # declare success if we can find them all.
1229 oname_parts = oname.split('.')
1270 oname_parts = oname.split('.')
1230 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1271 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1231 for nsname,ns in namespaces:
1272 for nsname,ns in namespaces:
1232 try:
1273 try:
1233 obj = ns[oname_head]
1274 obj = ns[oname_head]
1234 except KeyError:
1275 except KeyError:
1235 continue
1276 continue
1236 else:
1277 else:
1237 #print 'oname_rest:', oname_rest # dbg
1278 #print 'oname_rest:', oname_rest # dbg
1238 for part in oname_rest:
1279 for part in oname_rest:
1239 try:
1280 try:
1240 parent = obj
1281 parent = obj
1241 obj = getattr(obj,part)
1282 obj = getattr(obj,part)
1242 except:
1283 except:
1243 # Blanket except b/c some badly implemented objects
1284 # Blanket except b/c some badly implemented objects
1244 # allow __getattr__ to raise exceptions other than
1285 # allow __getattr__ to raise exceptions other than
1245 # AttributeError, which then crashes IPython.
1286 # AttributeError, which then crashes IPython.
1246 break
1287 break
1247 else:
1288 else:
1248 # If we finish the for loop (no break), we got all members
1289 # If we finish the for loop (no break), we got all members
1249 found = True
1290 found = True
1250 ospace = nsname
1291 ospace = nsname
1251 if ns == alias_ns:
1292 if ns == alias_ns:
1252 isalias = True
1293 isalias = True
1253 break # namespace loop
1294 break # namespace loop
1254
1295
1255 # Try to see if it's magic
1296 # Try to see if it's magic
1256 if not found:
1297 if not found:
1257 if oname.startswith(ESC_MAGIC):
1298 if oname.startswith(ESC_MAGIC):
1258 oname = oname[1:]
1299 oname = oname[1:]
1259 obj = getattr(self,'magic_'+oname,None)
1300 obj = getattr(self,'magic_'+oname,None)
1260 if obj is not None:
1301 if obj is not None:
1261 found = True
1302 found = True
1262 ospace = 'IPython internal'
1303 ospace = 'IPython internal'
1263 ismagic = True
1304 ismagic = True
1264
1305
1265 # Last try: special-case some literals like '', [], {}, etc:
1306 # Last try: special-case some literals like '', [], {}, etc:
1266 if not found and oname_head in ["''",'""','[]','{}','()']:
1307 if not found and oname_head in ["''",'""','[]','{}','()']:
1267 obj = eval(oname_head)
1308 obj = eval(oname_head)
1268 found = True
1309 found = True
1269 ospace = 'Interactive'
1310 ospace = 'Interactive'
1270
1311
1271 return {'found':found, 'obj':obj, 'namespace':ospace,
1312 return {'found':found, 'obj':obj, 'namespace':ospace,
1272 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1313 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1273
1314
1274 def _ofind_property(self, oname, info):
1315 def _ofind_property(self, oname, info):
1275 """Second part of object finding, to look for property details."""
1316 """Second part of object finding, to look for property details."""
1276 if info.found:
1317 if info.found:
1277 # Get the docstring of the class property if it exists.
1318 # Get the docstring of the class property if it exists.
1278 path = oname.split('.')
1319 path = oname.split('.')
1279 root = '.'.join(path[:-1])
1320 root = '.'.join(path[:-1])
1280 if info.parent is not None:
1321 if info.parent is not None:
1281 try:
1322 try:
1282 target = getattr(info.parent, '__class__')
1323 target = getattr(info.parent, '__class__')
1283 # The object belongs to a class instance.
1324 # The object belongs to a class instance.
1284 try:
1325 try:
1285 target = getattr(target, path[-1])
1326 target = getattr(target, path[-1])
1286 # The class defines the object.
1327 # The class defines the object.
1287 if isinstance(target, property):
1328 if isinstance(target, property):
1288 oname = root + '.__class__.' + path[-1]
1329 oname = root + '.__class__.' + path[-1]
1289 info = Struct(self._ofind(oname))
1330 info = Struct(self._ofind(oname))
1290 except AttributeError: pass
1331 except AttributeError: pass
1291 except AttributeError: pass
1332 except AttributeError: pass
1292
1333
1293 # We return either the new info or the unmodified input if the object
1334 # We return either the new info or the unmodified input if the object
1294 # hadn't been found
1335 # hadn't been found
1295 return info
1336 return info
1296
1337
1297 def _object_find(self, oname, namespaces=None):
1338 def _object_find(self, oname, namespaces=None):
1298 """Find an object and return a struct with info about it."""
1339 """Find an object and return a struct with info about it."""
1299 inf = Struct(self._ofind(oname, namespaces))
1340 inf = Struct(self._ofind(oname, namespaces))
1300 return Struct(self._ofind_property(oname, inf))
1341 return Struct(self._ofind_property(oname, inf))
1301
1342
1302 def _inspect(self, meth, oname, namespaces=None, **kw):
1343 def _inspect(self, meth, oname, namespaces=None, **kw):
1303 """Generic interface to the inspector system.
1344 """Generic interface to the inspector system.
1304
1345
1305 This function is meant to be called by pdef, pdoc & friends."""
1346 This function is meant to be called by pdef, pdoc & friends."""
1306 info = self._object_find(oname)
1347 info = self._object_find(oname)
1307 if info.found:
1348 if info.found:
1308 pmethod = getattr(self.inspector, meth)
1349 pmethod = getattr(self.inspector, meth)
1309 formatter = format_screen if info.ismagic else None
1350 formatter = format_screen if info.ismagic else None
1310 if meth == 'pdoc':
1351 if meth == 'pdoc':
1311 pmethod(info.obj, oname, formatter)
1352 pmethod(info.obj, oname, formatter)
1312 elif meth == 'pinfo':
1353 elif meth == 'pinfo':
1313 pmethod(info.obj, oname, formatter, info, **kw)
1354 pmethod(info.obj, oname, formatter, info, **kw)
1314 else:
1355 else:
1315 pmethod(info.obj, oname)
1356 pmethod(info.obj, oname)
1316 else:
1357 else:
1317 print 'Object `%s` not found.' % oname
1358 print 'Object `%s` not found.' % oname
1318 return 'not found' # so callers can take other action
1359 return 'not found' # so callers can take other action
1319
1360
1320 def object_inspect(self, oname):
1361 def object_inspect(self, oname):
1321 with self.builtin_trap:
1362 with self.builtin_trap:
1322 info = self._object_find(oname)
1363 info = self._object_find(oname)
1323 if info.found:
1364 if info.found:
1324 return self.inspector.info(info.obj, oname, info=info)
1365 return self.inspector.info(info.obj, oname, info=info)
1325 else:
1366 else:
1326 return oinspect.object_info(name=oname, found=False)
1367 return oinspect.object_info(name=oname, found=False)
1327
1368
1328 #-------------------------------------------------------------------------
1369 #-------------------------------------------------------------------------
1329 # Things related to history management
1370 # Things related to history management
1330 #-------------------------------------------------------------------------
1371 #-------------------------------------------------------------------------
1331
1372
1332 def init_history(self):
1373 def init_history(self):
1333 """Sets up the command history, and starts regular autosaves."""
1374 """Sets up the command history, and starts regular autosaves."""
1334 self.history_manager = HistoryManager(shell=self, config=self.config)
1375 self.history_manager = HistoryManager(shell=self, config=self.config)
1335
1376
1336 #-------------------------------------------------------------------------
1377 #-------------------------------------------------------------------------
1337 # Things related to exception handling and tracebacks (not debugging)
1378 # Things related to exception handling and tracebacks (not debugging)
1338 #-------------------------------------------------------------------------
1379 #-------------------------------------------------------------------------
1339
1380
1340 def init_traceback_handlers(self, custom_exceptions):
1381 def init_traceback_handlers(self, custom_exceptions):
1341 # Syntax error handler.
1382 # Syntax error handler.
1342 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1383 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1343
1384
1344 # The interactive one is initialized with an offset, meaning we always
1385 # The interactive one is initialized with an offset, meaning we always
1345 # want to remove the topmost item in the traceback, which is our own
1386 # want to remove the topmost item in the traceback, which is our own
1346 # internal code. Valid modes: ['Plain','Context','Verbose']
1387 # internal code. Valid modes: ['Plain','Context','Verbose']
1347 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1388 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1348 color_scheme='NoColor',
1389 color_scheme='NoColor',
1349 tb_offset = 1,
1390 tb_offset = 1,
1350 check_cache=self.compile.check_cache)
1391 check_cache=self.compile.check_cache)
1351
1392
1352 # The instance will store a pointer to the system-wide exception hook,
1393 # The instance will store a pointer to the system-wide exception hook,
1353 # so that runtime code (such as magics) can access it. This is because
1394 # so that runtime code (such as magics) can access it. This is because
1354 # during the read-eval loop, it may get temporarily overwritten.
1395 # during the read-eval loop, it may get temporarily overwritten.
1355 self.sys_excepthook = sys.excepthook
1396 self.sys_excepthook = sys.excepthook
1356
1397
1357 # and add any custom exception handlers the user may have specified
1398 # and add any custom exception handlers the user may have specified
1358 self.set_custom_exc(*custom_exceptions)
1399 self.set_custom_exc(*custom_exceptions)
1359
1400
1360 # Set the exception mode
1401 # Set the exception mode
1361 self.InteractiveTB.set_mode(mode=self.xmode)
1402 self.InteractiveTB.set_mode(mode=self.xmode)
1362
1403
1363 def set_custom_exc(self, exc_tuple, handler):
1404 def set_custom_exc(self, exc_tuple, handler):
1364 """set_custom_exc(exc_tuple,handler)
1405 """set_custom_exc(exc_tuple,handler)
1365
1406
1366 Set a custom exception handler, which will be called if any of the
1407 Set a custom exception handler, which will be called if any of the
1367 exceptions in exc_tuple occur in the mainloop (specifically, in the
1408 exceptions in exc_tuple occur in the mainloop (specifically, in the
1368 run_code() method.
1409 run_code() method.
1369
1410
1370 Inputs:
1411 Inputs:
1371
1412
1372 - exc_tuple: a *tuple* of valid exceptions to call the defined
1413 - exc_tuple: a *tuple* of valid exceptions to call the defined
1373 handler for. It is very important that you use a tuple, and NOT A
1414 handler for. It is very important that you use a tuple, and NOT A
1374 LIST here, because of the way Python's except statement works. If
1415 LIST here, because of the way Python's except statement works. If
1375 you only want to trap a single exception, use a singleton tuple:
1416 you only want to trap a single exception, use a singleton tuple:
1376
1417
1377 exc_tuple == (MyCustomException,)
1418 exc_tuple == (MyCustomException,)
1378
1419
1379 - handler: this must be defined as a function with the following
1420 - handler: this must be defined as a function with the following
1380 basic interface::
1421 basic interface::
1381
1422
1382 def my_handler(self, etype, value, tb, tb_offset=None)
1423 def my_handler(self, etype, value, tb, tb_offset=None)
1383 ...
1424 ...
1384 # The return value must be
1425 # The return value must be
1385 return structured_traceback
1426 return structured_traceback
1386
1427
1387 This will be made into an instance method (via types.MethodType)
1428 This will be made into an instance method (via types.MethodType)
1388 of IPython itself, and it will be called if any of the exceptions
1429 of IPython itself, and it will be called if any of the exceptions
1389 listed in the exc_tuple are caught. If the handler is None, an
1430 listed in the exc_tuple are caught. If the handler is None, an
1390 internal basic one is used, which just prints basic info.
1431 internal basic one is used, which just prints basic info.
1391
1432
1392 WARNING: by putting in your own exception handler into IPython's main
1433 WARNING: by putting in your own exception handler into IPython's main
1393 execution loop, you run a very good chance of nasty crashes. This
1434 execution loop, you run a very good chance of nasty crashes. This
1394 facility should only be used if you really know what you are doing."""
1435 facility should only be used if you really know what you are doing."""
1395
1436
1396 assert type(exc_tuple)==type(()) , \
1437 assert type(exc_tuple)==type(()) , \
1397 "The custom exceptions must be given AS A TUPLE."
1438 "The custom exceptions must be given AS A TUPLE."
1398
1439
1399 def dummy_handler(self,etype,value,tb):
1440 def dummy_handler(self,etype,value,tb):
1400 print '*** Simple custom exception handler ***'
1441 print '*** Simple custom exception handler ***'
1401 print 'Exception type :',etype
1442 print 'Exception type :',etype
1402 print 'Exception value:',value
1443 print 'Exception value:',value
1403 print 'Traceback :',tb
1444 print 'Traceback :',tb
1404 #print 'Source code :','\n'.join(self.buffer)
1445 #print 'Source code :','\n'.join(self.buffer)
1405
1446
1406 if handler is None: handler = dummy_handler
1447 if handler is None: handler = dummy_handler
1407
1448
1408 self.CustomTB = types.MethodType(handler,self)
1449 self.CustomTB = types.MethodType(handler,self)
1409 self.custom_exceptions = exc_tuple
1450 self.custom_exceptions = exc_tuple
1410
1451
1411 def excepthook(self, etype, value, tb):
1452 def excepthook(self, etype, value, tb):
1412 """One more defense for GUI apps that call sys.excepthook.
1453 """One more defense for GUI apps that call sys.excepthook.
1413
1454
1414 GUI frameworks like wxPython trap exceptions and call
1455 GUI frameworks like wxPython trap exceptions and call
1415 sys.excepthook themselves. I guess this is a feature that
1456 sys.excepthook themselves. I guess this is a feature that
1416 enables them to keep running after exceptions that would
1457 enables them to keep running after exceptions that would
1417 otherwise kill their mainloop. This is a bother for IPython
1458 otherwise kill their mainloop. This is a bother for IPython
1418 which excepts to catch all of the program exceptions with a try:
1459 which excepts to catch all of the program exceptions with a try:
1419 except: statement.
1460 except: statement.
1420
1461
1421 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1462 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1422 any app directly invokes sys.excepthook, it will look to the user like
1463 any app directly invokes sys.excepthook, it will look to the user like
1423 IPython crashed. In order to work around this, we can disable the
1464 IPython crashed. In order to work around this, we can disable the
1424 CrashHandler and replace it with this excepthook instead, which prints a
1465 CrashHandler and replace it with this excepthook instead, which prints a
1425 regular traceback using our InteractiveTB. In this fashion, apps which
1466 regular traceback using our InteractiveTB. In this fashion, apps which
1426 call sys.excepthook will generate a regular-looking exception from
1467 call sys.excepthook will generate a regular-looking exception from
1427 IPython, and the CrashHandler will only be triggered by real IPython
1468 IPython, and the CrashHandler will only be triggered by real IPython
1428 crashes.
1469 crashes.
1429
1470
1430 This hook should be used sparingly, only in places which are not likely
1471 This hook should be used sparingly, only in places which are not likely
1431 to be true IPython errors.
1472 to be true IPython errors.
1432 """
1473 """
1433 self.showtraceback((etype,value,tb),tb_offset=0)
1474 self.showtraceback((etype,value,tb),tb_offset=0)
1434
1475
1435 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1476 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1436 exception_only=False):
1477 exception_only=False):
1437 """Display the exception that just occurred.
1478 """Display the exception that just occurred.
1438
1479
1439 If nothing is known about the exception, this is the method which
1480 If nothing is known about the exception, this is the method which
1440 should be used throughout the code for presenting user tracebacks,
1481 should be used throughout the code for presenting user tracebacks,
1441 rather than directly invoking the InteractiveTB object.
1482 rather than directly invoking the InteractiveTB object.
1442
1483
1443 A specific showsyntaxerror() also exists, but this method can take
1484 A specific showsyntaxerror() also exists, but this method can take
1444 care of calling it if needed, so unless you are explicitly catching a
1485 care of calling it if needed, so unless you are explicitly catching a
1445 SyntaxError exception, don't try to analyze the stack manually and
1486 SyntaxError exception, don't try to analyze the stack manually and
1446 simply call this method."""
1487 simply call this method."""
1447
1488
1448 try:
1489 try:
1449 if exc_tuple is None:
1490 if exc_tuple is None:
1450 etype, value, tb = sys.exc_info()
1491 etype, value, tb = sys.exc_info()
1451 else:
1492 else:
1452 etype, value, tb = exc_tuple
1493 etype, value, tb = exc_tuple
1453
1494
1454 if etype is None:
1495 if etype is None:
1455 if hasattr(sys, 'last_type'):
1496 if hasattr(sys, 'last_type'):
1456 etype, value, tb = sys.last_type, sys.last_value, \
1497 etype, value, tb = sys.last_type, sys.last_value, \
1457 sys.last_traceback
1498 sys.last_traceback
1458 else:
1499 else:
1459 self.write_err('No traceback available to show.\n')
1500 self.write_err('No traceback available to show.\n')
1460 return
1501 return
1461
1502
1462 if etype is SyntaxError:
1503 if etype is SyntaxError:
1463 # Though this won't be called by syntax errors in the input
1504 # Though this won't be called by syntax errors in the input
1464 # line, there may be SyntaxError cases whith imported code.
1505 # line, there may be SyntaxError cases whith imported code.
1465 self.showsyntaxerror(filename)
1506 self.showsyntaxerror(filename)
1466 elif etype is UsageError:
1507 elif etype is UsageError:
1467 print "UsageError:", value
1508 print "UsageError:", value
1468 else:
1509 else:
1469 # WARNING: these variables are somewhat deprecated and not
1510 # WARNING: these variables are somewhat deprecated and not
1470 # necessarily safe to use in a threaded environment, but tools
1511 # necessarily safe to use in a threaded environment, but tools
1471 # like pdb depend on their existence, so let's set them. If we
1512 # like pdb depend on their existence, so let's set them. If we
1472 # find problems in the field, we'll need to revisit their use.
1513 # find problems in the field, we'll need to revisit their use.
1473 sys.last_type = etype
1514 sys.last_type = etype
1474 sys.last_value = value
1515 sys.last_value = value
1475 sys.last_traceback = tb
1516 sys.last_traceback = tb
1476 if etype in self.custom_exceptions:
1517 if etype in self.custom_exceptions:
1477 # FIXME: Old custom traceback objects may just return a
1518 # FIXME: Old custom traceback objects may just return a
1478 # string, in that case we just put it into a list
1519 # string, in that case we just put it into a list
1479 stb = self.CustomTB(etype, value, tb, tb_offset)
1520 stb = self.CustomTB(etype, value, tb, tb_offset)
1480 if isinstance(ctb, basestring):
1521 if isinstance(ctb, basestring):
1481 stb = [stb]
1522 stb = [stb]
1482 else:
1523 else:
1483 if exception_only:
1524 if exception_only:
1484 stb = ['An exception has occurred, use %tb to see '
1525 stb = ['An exception has occurred, use %tb to see '
1485 'the full traceback.\n']
1526 'the full traceback.\n']
1486 stb.extend(self.InteractiveTB.get_exception_only(etype,
1527 stb.extend(self.InteractiveTB.get_exception_only(etype,
1487 value))
1528 value))
1488 else:
1529 else:
1489 stb = self.InteractiveTB.structured_traceback(etype,
1530 stb = self.InteractiveTB.structured_traceback(etype,
1490 value, tb, tb_offset=tb_offset)
1531 value, tb, tb_offset=tb_offset)
1491
1532
1492 if self.call_pdb:
1533 if self.call_pdb:
1493 # drop into debugger
1534 # drop into debugger
1494 self.debugger(force=True)
1535 self.debugger(force=True)
1495
1536
1496 # Actually show the traceback
1537 # Actually show the traceback
1497 self._showtraceback(etype, value, stb)
1538 self._showtraceback(etype, value, stb)
1498
1539
1499 except KeyboardInterrupt:
1540 except KeyboardInterrupt:
1500 self.write_err("\nKeyboardInterrupt\n")
1541 self.write_err("\nKeyboardInterrupt\n")
1501
1542
1502 def _showtraceback(self, etype, evalue, stb):
1543 def _showtraceback(self, etype, evalue, stb):
1503 """Actually show a traceback.
1544 """Actually show a traceback.
1504
1545
1505 Subclasses may override this method to put the traceback on a different
1546 Subclasses may override this method to put the traceback on a different
1506 place, like a side channel.
1547 place, like a side channel.
1507 """
1548 """
1508 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1549 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1509
1550
1510 def showsyntaxerror(self, filename=None):
1551 def showsyntaxerror(self, filename=None):
1511 """Display the syntax error that just occurred.
1552 """Display the syntax error that just occurred.
1512
1553
1513 This doesn't display a stack trace because there isn't one.
1554 This doesn't display a stack trace because there isn't one.
1514
1555
1515 If a filename is given, it is stuffed in the exception instead
1556 If a filename is given, it is stuffed in the exception instead
1516 of what was there before (because Python's parser always uses
1557 of what was there before (because Python's parser always uses
1517 "<string>" when reading from a string).
1558 "<string>" when reading from a string).
1518 """
1559 """
1519 etype, value, last_traceback = sys.exc_info()
1560 etype, value, last_traceback = sys.exc_info()
1520
1561
1521 # See note about these variables in showtraceback() above
1562 # See note about these variables in showtraceback() above
1522 sys.last_type = etype
1563 sys.last_type = etype
1523 sys.last_value = value
1564 sys.last_value = value
1524 sys.last_traceback = last_traceback
1565 sys.last_traceback = last_traceback
1525
1566
1526 if filename and etype is SyntaxError:
1567 if filename and etype is SyntaxError:
1527 # Work hard to stuff the correct filename in the exception
1568 # Work hard to stuff the correct filename in the exception
1528 try:
1569 try:
1529 msg, (dummy_filename, lineno, offset, line) = value
1570 msg, (dummy_filename, lineno, offset, line) = value
1530 except:
1571 except:
1531 # Not the format we expect; leave it alone
1572 # Not the format we expect; leave it alone
1532 pass
1573 pass
1533 else:
1574 else:
1534 # Stuff in the right filename
1575 # Stuff in the right filename
1535 try:
1576 try:
1536 # Assume SyntaxError is a class exception
1577 # Assume SyntaxError is a class exception
1537 value = SyntaxError(msg, (filename, lineno, offset, line))
1578 value = SyntaxError(msg, (filename, lineno, offset, line))
1538 except:
1579 except:
1539 # If that failed, assume SyntaxError is a string
1580 # If that failed, assume SyntaxError is a string
1540 value = msg, (filename, lineno, offset, line)
1581 value = msg, (filename, lineno, offset, line)
1541 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1582 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1542 self._showtraceback(etype, value, stb)
1583 self._showtraceback(etype, value, stb)
1543
1584
1544 #-------------------------------------------------------------------------
1585 #-------------------------------------------------------------------------
1545 # Things related to readline
1586 # Things related to readline
1546 #-------------------------------------------------------------------------
1587 #-------------------------------------------------------------------------
1547
1588
1548 def init_readline(self):
1589 def init_readline(self):
1549 """Command history completion/saving/reloading."""
1590 """Command history completion/saving/reloading."""
1550
1591
1551 if self.readline_use:
1592 if self.readline_use:
1552 import IPython.utils.rlineimpl as readline
1593 import IPython.utils.rlineimpl as readline
1553
1594
1554 self.rl_next_input = None
1595 self.rl_next_input = None
1555 self.rl_do_indent = False
1596 self.rl_do_indent = False
1556
1597
1557 if not self.readline_use or not readline.have_readline:
1598 if not self.readline_use or not readline.have_readline:
1558 self.has_readline = False
1599 self.has_readline = False
1559 self.readline = None
1600 self.readline = None
1560 # Set a number of methods that depend on readline to be no-op
1601 # Set a number of methods that depend on readline to be no-op
1561 self.set_readline_completer = no_op
1602 self.set_readline_completer = no_op
1562 self.set_custom_completer = no_op
1603 self.set_custom_completer = no_op
1563 self.set_completer_frame = no_op
1604 self.set_completer_frame = no_op
1564 warn('Readline services not available or not loaded.')
1605 warn('Readline services not available or not loaded.')
1565 else:
1606 else:
1566 self.has_readline = True
1607 self.has_readline = True
1567 self.readline = readline
1608 self.readline = readline
1568 sys.modules['readline'] = readline
1609 sys.modules['readline'] = readline
1569
1610
1570 # Platform-specific configuration
1611 # Platform-specific configuration
1571 if os.name == 'nt':
1612 if os.name == 'nt':
1572 # FIXME - check with Frederick to see if we can harmonize
1613 # FIXME - check with Frederick to see if we can harmonize
1573 # naming conventions with pyreadline to avoid this
1614 # naming conventions with pyreadline to avoid this
1574 # platform-dependent check
1615 # platform-dependent check
1575 self.readline_startup_hook = readline.set_pre_input_hook
1616 self.readline_startup_hook = readline.set_pre_input_hook
1576 else:
1617 else:
1577 self.readline_startup_hook = readline.set_startup_hook
1618 self.readline_startup_hook = readline.set_startup_hook
1578
1619
1579 # Load user's initrc file (readline config)
1620 # Load user's initrc file (readline config)
1580 # Or if libedit is used, load editrc.
1621 # Or if libedit is used, load editrc.
1581 inputrc_name = os.environ.get('INPUTRC')
1622 inputrc_name = os.environ.get('INPUTRC')
1582 if inputrc_name is None:
1623 if inputrc_name is None:
1583 home_dir = get_home_dir()
1624 home_dir = get_home_dir()
1584 if home_dir is not None:
1625 if home_dir is not None:
1585 inputrc_name = '.inputrc'
1626 inputrc_name = '.inputrc'
1586 if readline.uses_libedit:
1627 if readline.uses_libedit:
1587 inputrc_name = '.editrc'
1628 inputrc_name = '.editrc'
1588 inputrc_name = os.path.join(home_dir, inputrc_name)
1629 inputrc_name = os.path.join(home_dir, inputrc_name)
1589 if os.path.isfile(inputrc_name):
1630 if os.path.isfile(inputrc_name):
1590 try:
1631 try:
1591 readline.read_init_file(inputrc_name)
1632 readline.read_init_file(inputrc_name)
1592 except:
1633 except:
1593 warn('Problems reading readline initialization file <%s>'
1634 warn('Problems reading readline initialization file <%s>'
1594 % inputrc_name)
1635 % inputrc_name)
1595
1636
1596 # Configure readline according to user's prefs
1637 # Configure readline according to user's prefs
1597 # This is only done if GNU readline is being used. If libedit
1638 # This is only done if GNU readline is being used. If libedit
1598 # is being used (as on Leopard) the readline config is
1639 # is being used (as on Leopard) the readline config is
1599 # not run as the syntax for libedit is different.
1640 # not run as the syntax for libedit is different.
1600 if not readline.uses_libedit:
1641 if not readline.uses_libedit:
1601 for rlcommand in self.readline_parse_and_bind:
1642 for rlcommand in self.readline_parse_and_bind:
1602 #print "loading rl:",rlcommand # dbg
1643 #print "loading rl:",rlcommand # dbg
1603 readline.parse_and_bind(rlcommand)
1644 readline.parse_and_bind(rlcommand)
1604
1645
1605 # Remove some chars from the delimiters list. If we encounter
1646 # Remove some chars from the delimiters list. If we encounter
1606 # unicode chars, discard them.
1647 # unicode chars, discard them.
1607 delims = readline.get_completer_delims().encode("ascii", "ignore")
1648 delims = readline.get_completer_delims().encode("ascii", "ignore")
1608 delims = delims.translate(None, self.readline_remove_delims)
1649 delims = delims.translate(None, self.readline_remove_delims)
1609 delims = delims.replace(ESC_MAGIC, '')
1650 delims = delims.replace(ESC_MAGIC, '')
1610 readline.set_completer_delims(delims)
1651 readline.set_completer_delims(delims)
1611 # otherwise we end up with a monster history after a while:
1652 # otherwise we end up with a monster history after a while:
1612 readline.set_history_length(self.history_length)
1653 readline.set_history_length(self.history_length)
1613
1654
1614 self.refill_readline_hist()
1655 self.refill_readline_hist()
1615 self.readline_no_record = ReadlineNoRecord(self)
1656 self.readline_no_record = ReadlineNoRecord(self)
1616
1657
1617 # Configure auto-indent for all platforms
1658 # Configure auto-indent for all platforms
1618 self.set_autoindent(self.autoindent)
1659 self.set_autoindent(self.autoindent)
1619
1660
1620 def refill_readline_hist(self):
1661 def refill_readline_hist(self):
1621 # Load the last 1000 lines from history
1662 # Load the last 1000 lines from history
1622 self.readline.clear_history()
1663 self.readline.clear_history()
1623 stdin_encoding = sys.stdin.encoding or "utf-8"
1664 stdin_encoding = sys.stdin.encoding or "utf-8"
1624 for _, _, cell in self.history_manager.get_tail(1000,
1665 for _, _, cell in self.history_manager.get_tail(1000,
1625 include_latest=True):
1666 include_latest=True):
1626 if cell.strip(): # Ignore blank lines
1667 if cell.strip(): # Ignore blank lines
1627 for line in cell.splitlines():
1668 for line in cell.splitlines():
1628 self.readline.add_history(line.encode(stdin_encoding))
1669 self.readline.add_history(line.encode(stdin_encoding))
1629
1670
1630 def set_next_input(self, s):
1671 def set_next_input(self, s):
1631 """ Sets the 'default' input string for the next command line.
1672 """ Sets the 'default' input string for the next command line.
1632
1673
1633 Requires readline.
1674 Requires readline.
1634
1675
1635 Example:
1676 Example:
1636
1677
1637 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1678 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1638 [D:\ipython]|2> Hello Word_ # cursor is here
1679 [D:\ipython]|2> Hello Word_ # cursor is here
1639 """
1680 """
1640
1681
1641 self.rl_next_input = s
1682 self.rl_next_input = s
1642
1683
1643 # Maybe move this to the terminal subclass?
1684 # Maybe move this to the terminal subclass?
1644 def pre_readline(self):
1685 def pre_readline(self):
1645 """readline hook to be used at the start of each line.
1686 """readline hook to be used at the start of each line.
1646
1687
1647 Currently it handles auto-indent only."""
1688 Currently it handles auto-indent only."""
1648
1689
1649 if self.rl_do_indent:
1690 if self.rl_do_indent:
1650 self.readline.insert_text(self._indent_current_str())
1691 self.readline.insert_text(self._indent_current_str())
1651 if self.rl_next_input is not None:
1692 if self.rl_next_input is not None:
1652 self.readline.insert_text(self.rl_next_input)
1693 self.readline.insert_text(self.rl_next_input)
1653 self.rl_next_input = None
1694 self.rl_next_input = None
1654
1695
1655 def _indent_current_str(self):
1696 def _indent_current_str(self):
1656 """return the current level of indentation as a string"""
1697 """return the current level of indentation as a string"""
1657 return self.input_splitter.indent_spaces * ' '
1698 return self.input_splitter.indent_spaces * ' '
1658
1699
1659 #-------------------------------------------------------------------------
1700 #-------------------------------------------------------------------------
1660 # Things related to text completion
1701 # Things related to text completion
1661 #-------------------------------------------------------------------------
1702 #-------------------------------------------------------------------------
1662
1703
1663 def init_completer(self):
1704 def init_completer(self):
1664 """Initialize the completion machinery.
1705 """Initialize the completion machinery.
1665
1706
1666 This creates completion machinery that can be used by client code,
1707 This creates completion machinery that can be used by client code,
1667 either interactively in-process (typically triggered by the readline
1708 either interactively in-process (typically triggered by the readline
1668 library), programatically (such as in test suites) or out-of-prcess
1709 library), programatically (such as in test suites) or out-of-prcess
1669 (typically over the network by remote frontends).
1710 (typically over the network by remote frontends).
1670 """
1711 """
1671 from IPython.core.completer import IPCompleter
1712 from IPython.core.completer import IPCompleter
1672 from IPython.core.completerlib import (module_completer,
1713 from IPython.core.completerlib import (module_completer,
1673 magic_run_completer, cd_completer)
1714 magic_run_completer, cd_completer)
1674
1715
1675 self.Completer = IPCompleter(self,
1716 self.Completer = IPCompleter(self,
1676 self.user_ns,
1717 self.user_ns,
1677 self.user_global_ns,
1718 self.user_global_ns,
1678 self.readline_omit__names,
1719 self.readline_omit__names,
1679 self.alias_manager.alias_table,
1720 self.alias_manager.alias_table,
1680 self.has_readline)
1721 self.has_readline)
1681
1722
1682 # Add custom completers to the basic ones built into IPCompleter
1723 # Add custom completers to the basic ones built into IPCompleter
1683 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1724 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1684 self.strdispatchers['complete_command'] = sdisp
1725 self.strdispatchers['complete_command'] = sdisp
1685 self.Completer.custom_completers = sdisp
1726 self.Completer.custom_completers = sdisp
1686
1727
1687 self.set_hook('complete_command', module_completer, str_key = 'import')
1728 self.set_hook('complete_command', module_completer, str_key = 'import')
1688 self.set_hook('complete_command', module_completer, str_key = 'from')
1729 self.set_hook('complete_command', module_completer, str_key = 'from')
1689 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1730 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1690 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1731 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1691
1732
1692 # Only configure readline if we truly are using readline. IPython can
1733 # Only configure readline if we truly are using readline. IPython can
1693 # do tab-completion over the network, in GUIs, etc, where readline
1734 # do tab-completion over the network, in GUIs, etc, where readline
1694 # itself may be absent
1735 # itself may be absent
1695 if self.has_readline:
1736 if self.has_readline:
1696 self.set_readline_completer()
1737 self.set_readline_completer()
1697
1738
1698 def complete(self, text, line=None, cursor_pos=None):
1739 def complete(self, text, line=None, cursor_pos=None):
1699 """Return the completed text and a list of completions.
1740 """Return the completed text and a list of completions.
1700
1741
1701 Parameters
1742 Parameters
1702 ----------
1743 ----------
1703
1744
1704 text : string
1745 text : string
1705 A string of text to be completed on. It can be given as empty and
1746 A string of text to be completed on. It can be given as empty and
1706 instead a line/position pair are given. In this case, the
1747 instead a line/position pair are given. In this case, the
1707 completer itself will split the line like readline does.
1748 completer itself will split the line like readline does.
1708
1749
1709 line : string, optional
1750 line : string, optional
1710 The complete line that text is part of.
1751 The complete line that text is part of.
1711
1752
1712 cursor_pos : int, optional
1753 cursor_pos : int, optional
1713 The position of the cursor on the input line.
1754 The position of the cursor on the input line.
1714
1755
1715 Returns
1756 Returns
1716 -------
1757 -------
1717 text : string
1758 text : string
1718 The actual text that was completed.
1759 The actual text that was completed.
1719
1760
1720 matches : list
1761 matches : list
1721 A sorted list with all possible completions.
1762 A sorted list with all possible completions.
1722
1763
1723 The optional arguments allow the completion to take more context into
1764 The optional arguments allow the completion to take more context into
1724 account, and are part of the low-level completion API.
1765 account, and are part of the low-level completion API.
1725
1766
1726 This is a wrapper around the completion mechanism, similar to what
1767 This is a wrapper around the completion mechanism, similar to what
1727 readline does at the command line when the TAB key is hit. By
1768 readline does at the command line when the TAB key is hit. By
1728 exposing it as a method, it can be used by other non-readline
1769 exposing it as a method, it can be used by other non-readline
1729 environments (such as GUIs) for text completion.
1770 environments (such as GUIs) for text completion.
1730
1771
1731 Simple usage example:
1772 Simple usage example:
1732
1773
1733 In [1]: x = 'hello'
1774 In [1]: x = 'hello'
1734
1775
1735 In [2]: _ip.complete('x.l')
1776 In [2]: _ip.complete('x.l')
1736 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1777 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1737 """
1778 """
1738
1779
1739 # Inject names into __builtin__ so we can complete on the added names.
1780 # Inject names into __builtin__ so we can complete on the added names.
1740 with self.builtin_trap:
1781 with self.builtin_trap:
1741 return self.Completer.complete(text, line, cursor_pos)
1782 return self.Completer.complete(text, line, cursor_pos)
1742
1783
1743 def set_custom_completer(self, completer, pos=0):
1784 def set_custom_completer(self, completer, pos=0):
1744 """Adds a new custom completer function.
1785 """Adds a new custom completer function.
1745
1786
1746 The position argument (defaults to 0) is the index in the completers
1787 The position argument (defaults to 0) is the index in the completers
1747 list where you want the completer to be inserted."""
1788 list where you want the completer to be inserted."""
1748
1789
1749 newcomp = types.MethodType(completer,self.Completer)
1790 newcomp = types.MethodType(completer,self.Completer)
1750 self.Completer.matchers.insert(pos,newcomp)
1791 self.Completer.matchers.insert(pos,newcomp)
1751
1792
1752 def set_readline_completer(self):
1793 def set_readline_completer(self):
1753 """Reset readline's completer to be our own."""
1794 """Reset readline's completer to be our own."""
1754 self.readline.set_completer(self.Completer.rlcomplete)
1795 self.readline.set_completer(self.Completer.rlcomplete)
1755
1796
1756 def set_completer_frame(self, frame=None):
1797 def set_completer_frame(self, frame=None):
1757 """Set the frame of the completer."""
1798 """Set the frame of the completer."""
1758 if frame:
1799 if frame:
1759 self.Completer.namespace = frame.f_locals
1800 self.Completer.namespace = frame.f_locals
1760 self.Completer.global_namespace = frame.f_globals
1801 self.Completer.global_namespace = frame.f_globals
1761 else:
1802 else:
1762 self.Completer.namespace = self.user_ns
1803 self.Completer.namespace = self.user_ns
1763 self.Completer.global_namespace = self.user_global_ns
1804 self.Completer.global_namespace = self.user_global_ns
1764
1805
1765 #-------------------------------------------------------------------------
1806 #-------------------------------------------------------------------------
1766 # Things related to magics
1807 # Things related to magics
1767 #-------------------------------------------------------------------------
1808 #-------------------------------------------------------------------------
1768
1809
1769 def init_magics(self):
1810 def init_magics(self):
1770 # FIXME: Move the color initialization to the DisplayHook, which
1811 # FIXME: Move the color initialization to the DisplayHook, which
1771 # should be split into a prompt manager and displayhook. We probably
1812 # should be split into a prompt manager and displayhook. We probably
1772 # even need a centralize colors management object.
1813 # even need a centralize colors management object.
1773 self.magic_colors(self.colors)
1814 self.magic_colors(self.colors)
1774 # History was moved to a separate module
1815 # History was moved to a separate module
1775 from . import history
1816 from . import history
1776 history.init_ipython(self)
1817 history.init_ipython(self)
1777
1818
1778 def magic(self,arg_s):
1819 def magic(self,arg_s):
1779 """Call a magic function by name.
1820 """Call a magic function by name.
1780
1821
1781 Input: a string containing the name of the magic function to call and
1822 Input: a string containing the name of the magic function to call and
1782 any additional arguments to be passed to the magic.
1823 any additional arguments to be passed to the magic.
1783
1824
1784 magic('name -opt foo bar') is equivalent to typing at the ipython
1825 magic('name -opt foo bar') is equivalent to typing at the ipython
1785 prompt:
1826 prompt:
1786
1827
1787 In[1]: %name -opt foo bar
1828 In[1]: %name -opt foo bar
1788
1829
1789 To call a magic without arguments, simply use magic('name').
1830 To call a magic without arguments, simply use magic('name').
1790
1831
1791 This provides a proper Python function to call IPython's magics in any
1832 This provides a proper Python function to call IPython's magics in any
1792 valid Python code you can type at the interpreter, including loops and
1833 valid Python code you can type at the interpreter, including loops and
1793 compound statements.
1834 compound statements.
1794 """
1835 """
1795 args = arg_s.split(' ',1)
1836 args = arg_s.split(' ',1)
1796 magic_name = args[0]
1837 magic_name = args[0]
1797 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1838 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1798
1839
1799 try:
1840 try:
1800 magic_args = args[1]
1841 magic_args = args[1]
1801 except IndexError:
1842 except IndexError:
1802 magic_args = ''
1843 magic_args = ''
1803 fn = getattr(self,'magic_'+magic_name,None)
1844 fn = getattr(self,'magic_'+magic_name,None)
1804 if fn is None:
1845 if fn is None:
1805 error("Magic function `%s` not found." % magic_name)
1846 error("Magic function `%s` not found." % magic_name)
1806 else:
1847 else:
1807 magic_args = self.var_expand(magic_args,1)
1848 magic_args = self.var_expand(magic_args,1)
1808 # Grab local namespace if we need it:
1849 # Grab local namespace if we need it:
1809 if getattr(fn, "needs_local_scope", False):
1850 if getattr(fn, "needs_local_scope", False):
1810 self._magic_locals = sys._getframe(1).f_locals
1851 self._magic_locals = sys._getframe(1).f_locals
1811 with self.builtin_trap:
1852 with self.builtin_trap:
1812 result = fn(magic_args)
1853 result = fn(magic_args)
1813 # Ensure we're not keeping object references around:
1854 # Ensure we're not keeping object references around:
1814 self._magic_locals = {}
1855 self._magic_locals = {}
1815 return result
1856 return result
1816
1857
1817 def define_magic(self, magicname, func):
1858 def define_magic(self, magicname, func):
1818 """Expose own function as magic function for ipython
1859 """Expose own function as magic function for ipython
1819
1860
1820 def foo_impl(self,parameter_s=''):
1861 def foo_impl(self,parameter_s=''):
1821 'My very own magic!. (Use docstrings, IPython reads them).'
1862 'My very own magic!. (Use docstrings, IPython reads them).'
1822 print 'Magic function. Passed parameter is between < >:'
1863 print 'Magic function. Passed parameter is between < >:'
1823 print '<%s>' % parameter_s
1864 print '<%s>' % parameter_s
1824 print 'The self object is:',self
1865 print 'The self object is:',self
1825
1866
1826 self.define_magic('foo',foo_impl)
1867 self.define_magic('foo',foo_impl)
1827 """
1868 """
1828
1869
1829 import new
1870 import new
1830 im = types.MethodType(func,self)
1871 im = types.MethodType(func,self)
1831 old = getattr(self, "magic_" + magicname, None)
1872 old = getattr(self, "magic_" + magicname, None)
1832 setattr(self, "magic_" + magicname, im)
1873 setattr(self, "magic_" + magicname, im)
1833 return old
1874 return old
1834
1875
1835 #-------------------------------------------------------------------------
1876 #-------------------------------------------------------------------------
1836 # Things related to macros
1877 # Things related to macros
1837 #-------------------------------------------------------------------------
1878 #-------------------------------------------------------------------------
1838
1879
1839 def define_macro(self, name, themacro):
1880 def define_macro(self, name, themacro):
1840 """Define a new macro
1881 """Define a new macro
1841
1882
1842 Parameters
1883 Parameters
1843 ----------
1884 ----------
1844 name : str
1885 name : str
1845 The name of the macro.
1886 The name of the macro.
1846 themacro : str or Macro
1887 themacro : str or Macro
1847 The action to do upon invoking the macro. If a string, a new
1888 The action to do upon invoking the macro. If a string, a new
1848 Macro object is created by passing the string to it.
1889 Macro object is created by passing the string to it.
1849 """
1890 """
1850
1891
1851 from IPython.core import macro
1892 from IPython.core import macro
1852
1893
1853 if isinstance(themacro, basestring):
1894 if isinstance(themacro, basestring):
1854 themacro = macro.Macro(themacro)
1895 themacro = macro.Macro(themacro)
1855 if not isinstance(themacro, macro.Macro):
1896 if not isinstance(themacro, macro.Macro):
1856 raise ValueError('A macro must be a string or a Macro instance.')
1897 raise ValueError('A macro must be a string or a Macro instance.')
1857 self.user_ns[name] = themacro
1898 self.user_ns[name] = themacro
1858
1899
1859 #-------------------------------------------------------------------------
1900 #-------------------------------------------------------------------------
1860 # Things related to the running of system commands
1901 # Things related to the running of system commands
1861 #-------------------------------------------------------------------------
1902 #-------------------------------------------------------------------------
1862
1903
1863 def system(self, cmd):
1904 def system(self, cmd):
1864 """Call the given cmd in a subprocess.
1905 """Call the given cmd in a subprocess.
1865
1906
1866 Parameters
1907 Parameters
1867 ----------
1908 ----------
1868 cmd : str
1909 cmd : str
1869 Command to execute (can not end in '&', as bacground processes are
1910 Command to execute (can not end in '&', as bacground processes are
1870 not supported.
1911 not supported.
1871 """
1912 """
1872 # We do not support backgrounding processes because we either use
1913 # We do not support backgrounding processes because we either use
1873 # pexpect or pipes to read from. Users can always just call
1914 # pexpect or pipes to read from. Users can always just call
1874 # os.system() if they really want a background process.
1915 # os.system() if they really want a background process.
1875 if cmd.endswith('&'):
1916 if cmd.endswith('&'):
1876 raise OSError("Background processes not supported.")
1917 raise OSError("Background processes not supported.")
1877
1918
1878 return system(self.var_expand(cmd, depth=2))
1919 return system(self.var_expand(cmd, depth=2))
1879
1920
1880 def getoutput(self, cmd, split=True):
1921 def getoutput(self, cmd, split=True):
1881 """Get output (possibly including stderr) from a subprocess.
1922 """Get output (possibly including stderr) from a subprocess.
1882
1923
1883 Parameters
1924 Parameters
1884 ----------
1925 ----------
1885 cmd : str
1926 cmd : str
1886 Command to execute (can not end in '&', as background processes are
1927 Command to execute (can not end in '&', as background processes are
1887 not supported.
1928 not supported.
1888 split : bool, optional
1929 split : bool, optional
1889
1930
1890 If True, split the output into an IPython SList. Otherwise, an
1931 If True, split the output into an IPython SList. Otherwise, an
1891 IPython LSString is returned. These are objects similar to normal
1932 IPython LSString is returned. These are objects similar to normal
1892 lists and strings, with a few convenience attributes for easier
1933 lists and strings, with a few convenience attributes for easier
1893 manipulation of line-based output. You can use '?' on them for
1934 manipulation of line-based output. You can use '?' on them for
1894 details.
1935 details.
1895 """
1936 """
1896 if cmd.endswith('&'):
1937 if cmd.endswith('&'):
1897 raise OSError("Background processes not supported.")
1938 raise OSError("Background processes not supported.")
1898 out = getoutput(self.var_expand(cmd, depth=2))
1939 out = getoutput(self.var_expand(cmd, depth=2))
1899 if split:
1940 if split:
1900 out = SList(out.splitlines())
1941 out = SList(out.splitlines())
1901 else:
1942 else:
1902 out = LSString(out)
1943 out = LSString(out)
1903 return out
1944 return out
1904
1945
1905 #-------------------------------------------------------------------------
1946 #-------------------------------------------------------------------------
1906 # Things related to aliases
1947 # Things related to aliases
1907 #-------------------------------------------------------------------------
1948 #-------------------------------------------------------------------------
1908
1949
1909 def init_alias(self):
1950 def init_alias(self):
1910 self.alias_manager = AliasManager(shell=self, config=self.config)
1951 self.alias_manager = AliasManager(shell=self, config=self.config)
1911 self.ns_table['alias'] = self.alias_manager.alias_table,
1952 self.ns_table['alias'] = self.alias_manager.alias_table,
1912
1953
1913 #-------------------------------------------------------------------------
1954 #-------------------------------------------------------------------------
1914 # Things related to extensions and plugins
1955 # Things related to extensions and plugins
1915 #-------------------------------------------------------------------------
1956 #-------------------------------------------------------------------------
1916
1957
1917 def init_extension_manager(self):
1958 def init_extension_manager(self):
1918 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1959 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1919
1960
1920 def init_plugin_manager(self):
1961 def init_plugin_manager(self):
1921 self.plugin_manager = PluginManager(config=self.config)
1962 self.plugin_manager = PluginManager(config=self.config)
1922
1963
1923 #-------------------------------------------------------------------------
1964 #-------------------------------------------------------------------------
1924 # Things related to payloads
1965 # Things related to payloads
1925 #-------------------------------------------------------------------------
1966 #-------------------------------------------------------------------------
1926
1967
1927 def init_payload(self):
1968 def init_payload(self):
1928 self.payload_manager = PayloadManager(config=self.config)
1969 self.payload_manager = PayloadManager(config=self.config)
1929
1970
1930 #-------------------------------------------------------------------------
1971 #-------------------------------------------------------------------------
1931 # Things related to the prefilter
1972 # Things related to the prefilter
1932 #-------------------------------------------------------------------------
1973 #-------------------------------------------------------------------------
1933
1974
1934 def init_prefilter(self):
1975 def init_prefilter(self):
1935 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1976 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1936 # Ultimately this will be refactored in the new interpreter code, but
1977 # Ultimately this will be refactored in the new interpreter code, but
1937 # for now, we should expose the main prefilter method (there's legacy
1978 # for now, we should expose the main prefilter method (there's legacy
1938 # code out there that may rely on this).
1979 # code out there that may rely on this).
1939 self.prefilter = self.prefilter_manager.prefilter_lines
1980 self.prefilter = self.prefilter_manager.prefilter_lines
1940
1981
1941 def auto_rewrite_input(self, cmd):
1982 def auto_rewrite_input(self, cmd):
1942 """Print to the screen the rewritten form of the user's command.
1983 """Print to the screen the rewritten form of the user's command.
1943
1984
1944 This shows visual feedback by rewriting input lines that cause
1985 This shows visual feedback by rewriting input lines that cause
1945 automatic calling to kick in, like::
1986 automatic calling to kick in, like::
1946
1987
1947 /f x
1988 /f x
1948
1989
1949 into::
1990 into::
1950
1991
1951 ------> f(x)
1992 ------> f(x)
1952
1993
1953 after the user's input prompt. This helps the user understand that the
1994 after the user's input prompt. This helps the user understand that the
1954 input line was transformed automatically by IPython.
1995 input line was transformed automatically by IPython.
1955 """
1996 """
1956 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1997 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1957
1998
1958 try:
1999 try:
1959 # plain ascii works better w/ pyreadline, on some machines, so
2000 # plain ascii works better w/ pyreadline, on some machines, so
1960 # we use it and only print uncolored rewrite if we have unicode
2001 # we use it and only print uncolored rewrite if we have unicode
1961 rw = str(rw)
2002 rw = str(rw)
1962 print >> IPython.utils.io.Term.cout, rw
2003 print >> IPython.utils.io.Term.cout, rw
1963 except UnicodeEncodeError:
2004 except UnicodeEncodeError:
1964 print "------> " + cmd
2005 print "------> " + cmd
1965
2006
1966 #-------------------------------------------------------------------------
2007 #-------------------------------------------------------------------------
1967 # Things related to extracting values/expressions from kernel and user_ns
2008 # Things related to extracting values/expressions from kernel and user_ns
1968 #-------------------------------------------------------------------------
2009 #-------------------------------------------------------------------------
1969
2010
1970 def _simple_error(self):
2011 def _simple_error(self):
1971 etype, value = sys.exc_info()[:2]
2012 etype, value = sys.exc_info()[:2]
1972 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2013 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1973
2014
1974 def user_variables(self, names):
2015 def user_variables(self, names):
1975 """Get a list of variable names from the user's namespace.
2016 """Get a list of variable names from the user's namespace.
1976
2017
1977 Parameters
2018 Parameters
1978 ----------
2019 ----------
1979 names : list of strings
2020 names : list of strings
1980 A list of names of variables to be read from the user namespace.
2021 A list of names of variables to be read from the user namespace.
1981
2022
1982 Returns
2023 Returns
1983 -------
2024 -------
1984 A dict, keyed by the input names and with the repr() of each value.
2025 A dict, keyed by the input names and with the repr() of each value.
1985 """
2026 """
1986 out = {}
2027 out = {}
1987 user_ns = self.user_ns
2028 user_ns = self.user_ns
1988 for varname in names:
2029 for varname in names:
1989 try:
2030 try:
1990 value = repr(user_ns[varname])
2031 value = repr(user_ns[varname])
1991 except:
2032 except:
1992 value = self._simple_error()
2033 value = self._simple_error()
1993 out[varname] = value
2034 out[varname] = value
1994 return out
2035 return out
1995
2036
1996 def user_expressions(self, expressions):
2037 def user_expressions(self, expressions):
1997 """Evaluate a dict of expressions in the user's namespace.
2038 """Evaluate a dict of expressions in the user's namespace.
1998
2039
1999 Parameters
2040 Parameters
2000 ----------
2041 ----------
2001 expressions : dict
2042 expressions : dict
2002 A dict with string keys and string values. The expression values
2043 A dict with string keys and string values. The expression values
2003 should be valid Python expressions, each of which will be evaluated
2044 should be valid Python expressions, each of which will be evaluated
2004 in the user namespace.
2045 in the user namespace.
2005
2046
2006 Returns
2047 Returns
2007 -------
2048 -------
2008 A dict, keyed like the input expressions dict, with the repr() of each
2049 A dict, keyed like the input expressions dict, with the repr() of each
2009 value.
2050 value.
2010 """
2051 """
2011 out = {}
2052 out = {}
2012 user_ns = self.user_ns
2053 user_ns = self.user_ns
2013 global_ns = self.user_global_ns
2054 global_ns = self.user_global_ns
2014 for key, expr in expressions.iteritems():
2055 for key, expr in expressions.iteritems():
2015 try:
2056 try:
2016 value = repr(eval(expr, global_ns, user_ns))
2057 value = repr(eval(expr, global_ns, user_ns))
2017 except:
2058 except:
2018 value = self._simple_error()
2059 value = self._simple_error()
2019 out[key] = value
2060 out[key] = value
2020 return out
2061 return out
2021
2062
2022 #-------------------------------------------------------------------------
2063 #-------------------------------------------------------------------------
2023 # Things related to the running of code
2064 # Things related to the running of code
2024 #-------------------------------------------------------------------------
2065 #-------------------------------------------------------------------------
2025
2066
2026 def ex(self, cmd):
2067 def ex(self, cmd):
2027 """Execute a normal python statement in user namespace."""
2068 """Execute a normal python statement in user namespace."""
2028 with self.builtin_trap:
2069 with self.builtin_trap:
2029 exec cmd in self.user_global_ns, self.user_ns
2070 exec cmd in self.user_global_ns, self.user_ns
2030
2071
2031 def ev(self, expr):
2072 def ev(self, expr):
2032 """Evaluate python expression expr in user namespace.
2073 """Evaluate python expression expr in user namespace.
2033
2074
2034 Returns the result of evaluation
2075 Returns the result of evaluation
2035 """
2076 """
2036 with self.builtin_trap:
2077 with self.builtin_trap:
2037 return eval(expr, self.user_global_ns, self.user_ns)
2078 return eval(expr, self.user_global_ns, self.user_ns)
2038
2079
2039 def safe_execfile(self, fname, *where, **kw):
2080 def safe_execfile(self, fname, *where, **kw):
2040 """A safe version of the builtin execfile().
2081 """A safe version of the builtin execfile().
2041
2082
2042 This version will never throw an exception, but instead print
2083 This version will never throw an exception, but instead print
2043 helpful error messages to the screen. This only works on pure
2084 helpful error messages to the screen. This only works on pure
2044 Python files with the .py extension.
2085 Python files with the .py extension.
2045
2086
2046 Parameters
2087 Parameters
2047 ----------
2088 ----------
2048 fname : string
2089 fname : string
2049 The name of the file to be executed.
2090 The name of the file to be executed.
2050 where : tuple
2091 where : tuple
2051 One or two namespaces, passed to execfile() as (globals,locals).
2092 One or two namespaces, passed to execfile() as (globals,locals).
2052 If only one is given, it is passed as both.
2093 If only one is given, it is passed as both.
2053 exit_ignore : bool (False)
2094 exit_ignore : bool (False)
2054 If True, then silence SystemExit for non-zero status (it is always
2095 If True, then silence SystemExit for non-zero status (it is always
2055 silenced for zero status, as it is so common).
2096 silenced for zero status, as it is so common).
2056 """
2097 """
2057 kw.setdefault('exit_ignore', False)
2098 kw.setdefault('exit_ignore', False)
2058
2099
2059 fname = os.path.abspath(os.path.expanduser(fname))
2100 fname = os.path.abspath(os.path.expanduser(fname))
2060 # Make sure we have a .py file
2101 # Make sure we have a .py file
2061 if not fname.endswith('.py'):
2102 if not fname.endswith('.py'):
2062 warn('File must end with .py to be run using execfile: <%s>' % fname)
2103 warn('File must end with .py to be run using execfile: <%s>' % fname)
2063
2104
2064 # Make sure we can open the file
2105 # Make sure we can open the file
2065 try:
2106 try:
2066 with open(fname) as thefile:
2107 with open(fname) as thefile:
2067 pass
2108 pass
2068 except:
2109 except:
2069 warn('Could not open file <%s> for safe execution.' % fname)
2110 warn('Could not open file <%s> for safe execution.' % fname)
2070 return
2111 return
2071
2112
2072 # Find things also in current directory. This is needed to mimic the
2113 # Find things also in current directory. This is needed to mimic the
2073 # behavior of running a script from the system command line, where
2114 # behavior of running a script from the system command line, where
2074 # Python inserts the script's directory into sys.path
2115 # Python inserts the script's directory into sys.path
2075 dname = os.path.dirname(fname)
2116 dname = os.path.dirname(fname)
2076
2117
2077 if isinstance(fname, unicode):
2118 if isinstance(fname, unicode):
2078 # execfile uses default encoding instead of filesystem encoding
2119 # execfile uses default encoding instead of filesystem encoding
2079 # so unicode filenames will fail
2120 # so unicode filenames will fail
2080 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2121 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2081
2122
2082 with prepended_to_syspath(dname):
2123 with prepended_to_syspath(dname):
2083 try:
2124 try:
2084 execfile(fname,*where)
2125 execfile(fname,*where)
2085 except SystemExit, status:
2126 except SystemExit, status:
2086 # If the call was made with 0 or None exit status (sys.exit(0)
2127 # If the call was made with 0 or None exit status (sys.exit(0)
2087 # or sys.exit() ), don't bother showing a traceback, as both of
2128 # or sys.exit() ), don't bother showing a traceback, as both of
2088 # these are considered normal by the OS:
2129 # these are considered normal by the OS:
2089 # > python -c'import sys;sys.exit(0)'; echo $?
2130 # > python -c'import sys;sys.exit(0)'; echo $?
2090 # 0
2131 # 0
2091 # > python -c'import sys;sys.exit()'; echo $?
2132 # > python -c'import sys;sys.exit()'; echo $?
2092 # 0
2133 # 0
2093 # For other exit status, we show the exception unless
2134 # For other exit status, we show the exception unless
2094 # explicitly silenced, but only in short form.
2135 # explicitly silenced, but only in short form.
2095 if status.code not in (0, None) and not kw['exit_ignore']:
2136 if status.code not in (0, None) and not kw['exit_ignore']:
2096 self.showtraceback(exception_only=True)
2137 self.showtraceback(exception_only=True)
2097 except:
2138 except:
2098 self.showtraceback()
2139 self.showtraceback()
2099
2140
2100 def safe_execfile_ipy(self, fname):
2141 def safe_execfile_ipy(self, fname):
2101 """Like safe_execfile, but for .ipy files with IPython syntax.
2142 """Like safe_execfile, but for .ipy files with IPython syntax.
2102
2143
2103 Parameters
2144 Parameters
2104 ----------
2145 ----------
2105 fname : str
2146 fname : str
2106 The name of the file to execute. The filename must have a
2147 The name of the file to execute. The filename must have a
2107 .ipy extension.
2148 .ipy extension.
2108 """
2149 """
2109 fname = os.path.abspath(os.path.expanduser(fname))
2150 fname = os.path.abspath(os.path.expanduser(fname))
2110
2151
2111 # Make sure we have a .py file
2152 # Make sure we have a .py file
2112 if not fname.endswith('.ipy'):
2153 if not fname.endswith('.ipy'):
2113 warn('File must end with .py to be run using execfile: <%s>' % fname)
2154 warn('File must end with .py to be run using execfile: <%s>' % fname)
2114
2155
2115 # Make sure we can open the file
2156 # Make sure we can open the file
2116 try:
2157 try:
2117 with open(fname) as thefile:
2158 with open(fname) as thefile:
2118 pass
2159 pass
2119 except:
2160 except:
2120 warn('Could not open file <%s> for safe execution.' % fname)
2161 warn('Could not open file <%s> for safe execution.' % fname)
2121 return
2162 return
2122
2163
2123 # Find things also in current directory. This is needed to mimic the
2164 # Find things also in current directory. This is needed to mimic the
2124 # behavior of running a script from the system command line, where
2165 # behavior of running a script from the system command line, where
2125 # Python inserts the script's directory into sys.path
2166 # Python inserts the script's directory into sys.path
2126 dname = os.path.dirname(fname)
2167 dname = os.path.dirname(fname)
2127
2168
2128 with prepended_to_syspath(dname):
2169 with prepended_to_syspath(dname):
2129 try:
2170 try:
2130 with open(fname) as thefile:
2171 with open(fname) as thefile:
2131 # self.run_cell currently captures all exceptions
2172 # self.run_cell currently captures all exceptions
2132 # raised in user code. It would be nice if there were
2173 # raised in user code. It would be nice if there were
2133 # versions of runlines, execfile that did raise, so
2174 # versions of runlines, execfile that did raise, so
2134 # we could catch the errors.
2175 # we could catch the errors.
2135 self.run_cell(thefile.read(), store_history=False)
2176 self.run_cell(thefile.read(), store_history=False)
2136 except:
2177 except:
2137 self.showtraceback()
2178 self.showtraceback()
2138 warn('Unknown failure executing file: <%s>' % fname)
2179 warn('Unknown failure executing file: <%s>' % fname)
2139
2180
2140 def run_cell(self, raw_cell, store_history=True):
2181 def run_cell(self, raw_cell, store_history=True):
2141 """Run a complete IPython cell.
2182 """Run a complete IPython cell.
2142
2183
2143 Parameters
2184 Parameters
2144 ----------
2185 ----------
2145 raw_cell : str
2186 raw_cell : str
2146 The code (including IPython code such as %magic functions) to run.
2187 The code (including IPython code such as %magic functions) to run.
2147 store_history : bool
2188 store_history : bool
2148 If True, the raw and translated cell will be stored in IPython's
2189 If True, the raw and translated cell will be stored in IPython's
2149 history. For user code calling back into IPython's machinery, this
2190 history. For user code calling back into IPython's machinery, this
2150 should be set to False.
2191 should be set to False.
2151 """
2192 """
2152 if (not raw_cell) or raw_cell.isspace():
2193 if (not raw_cell) or raw_cell.isspace():
2153 return
2194 return
2154
2195
2155 for line in raw_cell.splitlines():
2196 for line in raw_cell.splitlines():
2156 self.input_splitter.push(line)
2197 self.input_splitter.push(line)
2157 cell = self.input_splitter.source_reset()
2198 cell = self.input_splitter.source_reset()
2158
2199
2159 with self.builtin_trap:
2200 with self.builtin_trap:
2160 if len(cell.splitlines()) == 1:
2201 if len(cell.splitlines()) == 1:
2161 cell = self.prefilter_manager.prefilter_lines(cell)
2202 cell = self.prefilter_manager.prefilter_lines(cell)
2162
2203
2163 # Store raw and processed history
2204 # Store raw and processed history
2164 if store_history:
2205 if store_history:
2165 self.history_manager.store_inputs(self.execution_count,
2206 self.history_manager.store_inputs(self.execution_count,
2166 cell, raw_cell)
2207 cell, raw_cell)
2167
2208
2168 self.logger.log(cell, raw_cell)
2209 self.logger.log(cell, raw_cell)
2169
2210
2170 cell_name = self.compile.cache(cell, self.execution_count)
2211 cell_name = self.compile.cache(cell, self.execution_count)
2171
2212
2172 with self.display_trap:
2213 with self.display_trap:
2173 try:
2214 try:
2174 code_ast = ast.parse(cell, filename=cell_name)
2215 code_ast = ast.parse(cell, filename=cell_name)
2175 except (OverflowError, SyntaxError, ValueError, TypeError,
2216 except (OverflowError, SyntaxError, ValueError, TypeError,
2176 MemoryError):
2217 MemoryError):
2177 self.showsyntaxerror()
2218 self.showsyntaxerror()
2178 self.execution_count += 1
2219 self.execution_count += 1
2179 return None
2220 return None
2180
2221
2181 self.run_ast_nodes(code_ast.body, cell_name,
2222 self.run_ast_nodes(code_ast.body, cell_name,
2182 interactivity="last_expr")
2223 interactivity="last_expr")
2183
2224
2184 # Execute any registered post-execution functions.
2225 # Execute any registered post-execution functions.
2185 for func, status in self._post_execute.iteritems():
2226 for func, status in self._post_execute.iteritems():
2186 if not status:
2227 if not status:
2187 continue
2228 continue
2188 try:
2229 try:
2189 func()
2230 func()
2190 except:
2231 except:
2191 self.showtraceback()
2232 self.showtraceback()
2192 # Deactivate failing function
2233 # Deactivate failing function
2193 self._post_execute[func] = False
2234 self._post_execute[func] = False
2194
2235
2195 if store_history:
2236 if store_history:
2196 # Write output to the database. Does nothing unless
2237 # Write output to the database. Does nothing unless
2197 # history output logging is enabled.
2238 # history output logging is enabled.
2198 self.history_manager.store_output(self.execution_count)
2239 self.history_manager.store_output(self.execution_count)
2199 # Each cell is a *single* input, regardless of how many lines it has
2240 # Each cell is a *single* input, regardless of how many lines it has
2200 self.execution_count += 1
2241 self.execution_count += 1
2201
2242
2202 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2243 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2203 """Run a sequence of AST nodes. The execution mode depends on the
2244 """Run a sequence of AST nodes. The execution mode depends on the
2204 interactivity parameter.
2245 interactivity parameter.
2205
2246
2206 Parameters
2247 Parameters
2207 ----------
2248 ----------
2208 nodelist : list
2249 nodelist : list
2209 A sequence of AST nodes to run.
2250 A sequence of AST nodes to run.
2210 cell_name : str
2251 cell_name : str
2211 Will be passed to the compiler as the filename of the cell. Typically
2252 Will be passed to the compiler as the filename of the cell. Typically
2212 the value returned by ip.compile.cache(cell).
2253 the value returned by ip.compile.cache(cell).
2213 interactivity : str
2254 interactivity : str
2214 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2255 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2215 run interactively (displaying output from expressions). 'last_expr'
2256 run interactively (displaying output from expressions). 'last_expr'
2216 will run the last node interactively only if it is an expression (i.e.
2257 will run the last node interactively only if it is an expression (i.e.
2217 expressions in loops or other blocks are not displayed. Other values
2258 expressions in loops or other blocks are not displayed. Other values
2218 for this parameter will raise a ValueError.
2259 for this parameter will raise a ValueError.
2219 """
2260 """
2220 if not nodelist:
2261 if not nodelist:
2221 return
2262 return
2222
2263
2223 if interactivity == 'last_expr':
2264 if interactivity == 'last_expr':
2224 if isinstance(nodelist[-1], ast.Expr):
2265 if isinstance(nodelist[-1], ast.Expr):
2225 interactivity = "last"
2266 interactivity = "last"
2226 else:
2267 else:
2227 interactivity = "none"
2268 interactivity = "none"
2228
2269
2229 if interactivity == 'none':
2270 if interactivity == 'none':
2230 to_run_exec, to_run_interactive = nodelist, []
2271 to_run_exec, to_run_interactive = nodelist, []
2231 elif interactivity == 'last':
2272 elif interactivity == 'last':
2232 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2273 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2233 elif interactivity == 'all':
2274 elif interactivity == 'all':
2234 to_run_exec, to_run_interactive = [], nodelist
2275 to_run_exec, to_run_interactive = [], nodelist
2235 else:
2276 else:
2236 raise ValueError("Interactivity was %r" % interactivity)
2277 raise ValueError("Interactivity was %r" % interactivity)
2237
2278
2238 exec_count = self.execution_count
2279 exec_count = self.execution_count
2239
2280
2240 for i, node in enumerate(to_run_exec):
2281 for i, node in enumerate(to_run_exec):
2241 mod = ast.Module([node])
2282 mod = ast.Module([node])
2242 code = self.compile(mod, cell_name, "exec")
2283 code = self.compile(mod, cell_name, "exec")
2243 if self.run_code(code):
2284 if self.run_code(code):
2244 return True
2285 return True
2245
2286
2246 for i, node in enumerate(to_run_interactive):
2287 for i, node in enumerate(to_run_interactive):
2247 mod = ast.Interactive([node])
2288 mod = ast.Interactive([node])
2248 code = self.compile(mod, cell_name, "single")
2289 code = self.compile(mod, cell_name, "single")
2249 if self.run_code(code):
2290 if self.run_code(code):
2250 return True
2291 return True
2251
2292
2252 return False
2293 return False
2253
2294
2254 def run_code(self, code_obj):
2295 def run_code(self, code_obj):
2255 """Execute a code object.
2296 """Execute a code object.
2256
2297
2257 When an exception occurs, self.showtraceback() is called to display a
2298 When an exception occurs, self.showtraceback() is called to display a
2258 traceback.
2299 traceback.
2259
2300
2260 Parameters
2301 Parameters
2261 ----------
2302 ----------
2262 code_obj : code object
2303 code_obj : code object
2263 A compiled code object, to be executed
2304 A compiled code object, to be executed
2264 post_execute : bool [default: True]
2305 post_execute : bool [default: True]
2265 whether to call post_execute hooks after this particular execution.
2306 whether to call post_execute hooks after this particular execution.
2266
2307
2267 Returns
2308 Returns
2268 -------
2309 -------
2269 False : successful execution.
2310 False : successful execution.
2270 True : an error occurred.
2311 True : an error occurred.
2271 """
2312 """
2272
2313
2273 # Set our own excepthook in case the user code tries to call it
2314 # Set our own excepthook in case the user code tries to call it
2274 # directly, so that the IPython crash handler doesn't get triggered
2315 # directly, so that the IPython crash handler doesn't get triggered
2275 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2316 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2276
2317
2277 # we save the original sys.excepthook in the instance, in case config
2318 # we save the original sys.excepthook in the instance, in case config
2278 # code (such as magics) needs access to it.
2319 # code (such as magics) needs access to it.
2279 self.sys_excepthook = old_excepthook
2320 self.sys_excepthook = old_excepthook
2280 outflag = 1 # happens in more places, so it's easier as default
2321 outflag = 1 # happens in more places, so it's easier as default
2281 try:
2322 try:
2282 try:
2323 try:
2283 self.hooks.pre_run_code_hook()
2324 self.hooks.pre_run_code_hook()
2284 #rprint('Running code', repr(code_obj)) # dbg
2325 #rprint('Running code', repr(code_obj)) # dbg
2285 exec code_obj in self.user_global_ns, self.user_ns
2326 exec code_obj in self.user_global_ns, self.user_ns
2286 finally:
2327 finally:
2287 # Reset our crash handler in place
2328 # Reset our crash handler in place
2288 sys.excepthook = old_excepthook
2329 sys.excepthook = old_excepthook
2289 except SystemExit:
2330 except SystemExit:
2290 self.showtraceback(exception_only=True)
2331 self.showtraceback(exception_only=True)
2291 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2332 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2292 except self.custom_exceptions:
2333 except self.custom_exceptions:
2293 etype,value,tb = sys.exc_info()
2334 etype,value,tb = sys.exc_info()
2294 self.CustomTB(etype,value,tb)
2335 self.CustomTB(etype,value,tb)
2295 except:
2336 except:
2296 self.showtraceback()
2337 self.showtraceback()
2297 else:
2338 else:
2298 outflag = 0
2339 outflag = 0
2299 if softspace(sys.stdout, 0):
2340 if softspace(sys.stdout, 0):
2300 print
2341 print
2301
2342
2302 return outflag
2343 return outflag
2303
2344
2304 # For backwards compatibility
2345 # For backwards compatibility
2305 runcode = run_code
2346 runcode = run_code
2306
2347
2307 #-------------------------------------------------------------------------
2348 #-------------------------------------------------------------------------
2308 # Things related to GUI support and pylab
2349 # Things related to GUI support and pylab
2309 #-------------------------------------------------------------------------
2350 #-------------------------------------------------------------------------
2310
2351
2311 def enable_pylab(self, gui=None):
2352 def enable_pylab(self, gui=None):
2312 raise NotImplementedError('Implement enable_pylab in a subclass')
2353 raise NotImplementedError('Implement enable_pylab in a subclass')
2313
2354
2314 #-------------------------------------------------------------------------
2355 #-------------------------------------------------------------------------
2315 # Utilities
2356 # Utilities
2316 #-------------------------------------------------------------------------
2357 #-------------------------------------------------------------------------
2317
2358
2318 def var_expand(self,cmd,depth=0):
2359 def var_expand(self,cmd,depth=0):
2319 """Expand python variables in a string.
2360 """Expand python variables in a string.
2320
2361
2321 The depth argument indicates how many frames above the caller should
2362 The depth argument indicates how many frames above the caller should
2322 be walked to look for the local namespace where to expand variables.
2363 be walked to look for the local namespace where to expand variables.
2323
2364
2324 The global namespace for expansion is always the user's interactive
2365 The global namespace for expansion is always the user's interactive
2325 namespace.
2366 namespace.
2326 """
2367 """
2327 res = ItplNS(cmd, self.user_ns, # globals
2368 res = ItplNS(cmd, self.user_ns, # globals
2328 # Skip our own frame in searching for locals:
2369 # Skip our own frame in searching for locals:
2329 sys._getframe(depth+1).f_locals # locals
2370 sys._getframe(depth+1).f_locals # locals
2330 )
2371 )
2331 return str(res).decode(res.codec)
2372 return str(res).decode(res.codec)
2332
2373
2333 def mktempfile(self, data=None, prefix='ipython_edit_'):
2374 def mktempfile(self, data=None, prefix='ipython_edit_'):
2334 """Make a new tempfile and return its filename.
2375 """Make a new tempfile and return its filename.
2335
2376
2336 This makes a call to tempfile.mktemp, but it registers the created
2377 This makes a call to tempfile.mktemp, but it registers the created
2337 filename internally so ipython cleans it up at exit time.
2378 filename internally so ipython cleans it up at exit time.
2338
2379
2339 Optional inputs:
2380 Optional inputs:
2340
2381
2341 - data(None): if data is given, it gets written out to the temp file
2382 - data(None): if data is given, it gets written out to the temp file
2342 immediately, and the file is closed again."""
2383 immediately, and the file is closed again."""
2343
2384
2344 filename = tempfile.mktemp('.py', prefix)
2385 filename = tempfile.mktemp('.py', prefix)
2345 self.tempfiles.append(filename)
2386 self.tempfiles.append(filename)
2346
2387
2347 if data:
2388 if data:
2348 tmp_file = open(filename,'w')
2389 tmp_file = open(filename,'w')
2349 tmp_file.write(data)
2390 tmp_file.write(data)
2350 tmp_file.close()
2391 tmp_file.close()
2351 return filename
2392 return filename
2352
2393
2353 # TODO: This should be removed when Term is refactored.
2394 # TODO: This should be removed when Term is refactored.
2354 def write(self,data):
2395 def write(self,data):
2355 """Write a string to the default output"""
2396 """Write a string to the default output"""
2356 io.Term.cout.write(data)
2397 io.Term.cout.write(data)
2357
2398
2358 # TODO: This should be removed when Term is refactored.
2399 # TODO: This should be removed when Term is refactored.
2359 def write_err(self,data):
2400 def write_err(self,data):
2360 """Write a string to the default error output"""
2401 """Write a string to the default error output"""
2361 io.Term.cerr.write(data)
2402 io.Term.cerr.write(data)
2362
2403
2363 def ask_yes_no(self,prompt,default=True):
2404 def ask_yes_no(self,prompt,default=True):
2364 if self.quiet:
2405 if self.quiet:
2365 return True
2406 return True
2366 return ask_yes_no(prompt,default)
2407 return ask_yes_no(prompt,default)
2367
2408
2368 def show_usage(self):
2409 def show_usage(self):
2369 """Show a usage message"""
2410 """Show a usage message"""
2370 page.page(IPython.core.usage.interactive_usage)
2411 page.page(IPython.core.usage.interactive_usage)
2371
2412
2372 def find_user_code(self, target, raw=True):
2413 def find_user_code(self, target, raw=True):
2373 """Get a code string from history, file, or a string or macro.
2414 """Get a code string from history, file, or a string or macro.
2374
2415
2375 This is mainly used by magic functions.
2416 This is mainly used by magic functions.
2376
2417
2377 Parameters
2418 Parameters
2378 ----------
2419 ----------
2379 target : str
2420 target : str
2380 A string specifying code to retrieve. This will be tried respectively
2421 A string specifying code to retrieve. This will be tried respectively
2381 as: ranges of input history (see %history for syntax), a filename, or
2422 as: ranges of input history (see %history for syntax), a filename, or
2382 an expression evaluating to a string or Macro in the user namespace.
2423 an expression evaluating to a string or Macro in the user namespace.
2383 raw : bool
2424 raw : bool
2384 If true (default), retrieve raw history. Has no effect on the other
2425 If true (default), retrieve raw history. Has no effect on the other
2385 retrieval mechanisms.
2426 retrieval mechanisms.
2386
2427
2387 Returns
2428 Returns
2388 -------
2429 -------
2389 A string of code.
2430 A string of code.
2390
2431
2391 ValueError is raised if nothing is found, and TypeError if it evaluates
2432 ValueError is raised if nothing is found, and TypeError if it evaluates
2392 to an object of another type. In each case, .args[0] is a printable
2433 to an object of another type. In each case, .args[0] is a printable
2393 message.
2434 message.
2394 """
2435 """
2395 code = self.extract_input_lines(target, raw=raw) # Grab history
2436 code = self.extract_input_lines(target, raw=raw) # Grab history
2396 if code:
2437 if code:
2397 return code
2438 return code
2398 if os.path.isfile(target): # Read file
2439 if os.path.isfile(target): # Read file
2399 return open(target, "r").read()
2440 return open(target, "r").read()
2400
2441
2401 try: # User namespace
2442 try: # User namespace
2402 codeobj = eval(target, self.user_ns)
2443 codeobj = eval(target, self.user_ns)
2403 except Exception:
2444 except Exception:
2404 raise ValueError(("'%s' was not found in history, as a file, nor in"
2445 raise ValueError(("'%s' was not found in history, as a file, nor in"
2405 " the user namespace.") % target)
2446 " the user namespace.") % target)
2406 if isinstance(codeobj, basestring):
2447 if isinstance(codeobj, basestring):
2407 return codeobj
2448 return codeobj
2408 elif isinstance(codeobj, Macro):
2449 elif isinstance(codeobj, Macro):
2409 return codeobj.value
2450 return codeobj.value
2410
2451
2411 raise TypeError("%s is neither a string nor a macro." % target,
2452 raise TypeError("%s is neither a string nor a macro." % target,
2412 codeobj)
2453 codeobj)
2413
2454
2414 #-------------------------------------------------------------------------
2455 #-------------------------------------------------------------------------
2415 # Things related to IPython exiting
2456 # Things related to IPython exiting
2416 #-------------------------------------------------------------------------
2457 #-------------------------------------------------------------------------
2417 def atexit_operations(self):
2458 def atexit_operations(self):
2418 """This will be executed at the time of exit.
2459 """This will be executed at the time of exit.
2419
2460
2420 Cleanup operations and saving of persistent data that is done
2461 Cleanup operations and saving of persistent data that is done
2421 unconditionally by IPython should be performed here.
2462 unconditionally by IPython should be performed here.
2422
2463
2423 For things that may depend on startup flags or platform specifics (such
2464 For things that may depend on startup flags or platform specifics (such
2424 as having readline or not), register a separate atexit function in the
2465 as having readline or not), register a separate atexit function in the
2425 code that has the appropriate information, rather than trying to
2466 code that has the appropriate information, rather than trying to
2426 clutter
2467 clutter
2427 """
2468 """
2428 # Cleanup all tempfiles left around
2469 # Cleanup all tempfiles left around
2429 for tfile in self.tempfiles:
2470 for tfile in self.tempfiles:
2430 try:
2471 try:
2431 os.unlink(tfile)
2472 os.unlink(tfile)
2432 except OSError:
2473 except OSError:
2433 pass
2474 pass
2434
2475
2435 # Close the history session (this stores the end time and line count)
2476 # Close the history session (this stores the end time and line count)
2436 self.history_manager.end_session()
2477 self.history_manager.end_session()
2437
2478
2438 # Clear all user namespaces to release all references cleanly.
2479 # Clear all user namespaces to release all references cleanly.
2439 self.reset(new_session=False)
2480 self.reset(new_session=False)
2440
2481
2441 # Run user hooks
2482 # Run user hooks
2442 self.hooks.shutdown_hook()
2483 self.hooks.shutdown_hook()
2443
2484
2444 def cleanup(self):
2485 def cleanup(self):
2445 self.restore_sys_module_state()
2486 self.restore_sys_module_state()
2446
2487
2447
2488
2448 class InteractiveShellABC(object):
2489 class InteractiveShellABC(object):
2449 """An abstract base class for InteractiveShell."""
2490 """An abstract base class for InteractiveShell."""
2450 __metaclass__ = abc.ABCMeta
2491 __metaclass__ = abc.ABCMeta
2451
2492
2452 InteractiveShellABC.register(InteractiveShell)
2493 InteractiveShellABC.register(InteractiveShell)
@@ -1,741 +1,743 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.utils.traitlets.
4 Tests for IPython.utils.traitlets.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Enthought, Inc. Some of the code in this file comes from enthought.traits
9 * Enthought, Inc. Some of the code in this file comes from enthought.traits
10 and is licensed under the BSD license. Also, many of the ideas also come
10 and is licensed under the BSD license. Also, many of the ideas also come
11 from enthought.traits even though our implementation is very different.
11 from enthought.traits even though our implementation is very different.
12 """
12 """
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2009 The IPython Development Team
15 # Copyright (C) 2008-2009 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from unittest import TestCase
25 from unittest import TestCase
26
26
27 from IPython.utils.traitlets import (
27 from IPython.utils.traitlets import (
28 HasTraits, MetaHasTraits, TraitType, Any,
28 HasTraits, MetaHasTraits, TraitType, Any,
29 Int, Long, Float, Complex, Str, Unicode, TraitError,
29 Int, Long, Float, Complex, Str, Unicode, TraitError,
30 Undefined, Type, This, Instance, TCPAddress
30 Undefined, Type, This, Instance, TCPAddress
31 )
31 )
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Helper classes for testing
35 # Helper classes for testing
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class HasTraitsStub(HasTraits):
39 class HasTraitsStub(HasTraits):
40
40
41 def _notify_trait(self, name, old, new):
41 def _notify_trait(self, name, old, new):
42 self._notify_name = name
42 self._notify_name = name
43 self._notify_old = old
43 self._notify_old = old
44 self._notify_new = new
44 self._notify_new = new
45
45
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Test classes
48 # Test classes
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51
51
52 class TestTraitType(TestCase):
52 class TestTraitType(TestCase):
53
53
54 def test_get_undefined(self):
54 def test_get_undefined(self):
55 class A(HasTraits):
55 class A(HasTraits):
56 a = TraitType
56 a = TraitType
57 a = A()
57 a = A()
58 self.assertEquals(a.a, Undefined)
58 self.assertEquals(a.a, Undefined)
59
59
60 def test_set(self):
60 def test_set(self):
61 class A(HasTraitsStub):
61 class A(HasTraitsStub):
62 a = TraitType
62 a = TraitType
63
63
64 a = A()
64 a = A()
65 a.a = 10
65 a.a = 10
66 self.assertEquals(a.a, 10)
66 self.assertEquals(a.a, 10)
67 self.assertEquals(a._notify_name, 'a')
67 self.assertEquals(a._notify_name, 'a')
68 self.assertEquals(a._notify_old, Undefined)
68 self.assertEquals(a._notify_old, Undefined)
69 self.assertEquals(a._notify_new, 10)
69 self.assertEquals(a._notify_new, 10)
70
70
71 def test_validate(self):
71 def test_validate(self):
72 class MyTT(TraitType):
72 class MyTT(TraitType):
73 def validate(self, inst, value):
73 def validate(self, inst, value):
74 return -1
74 return -1
75 class A(HasTraitsStub):
75 class A(HasTraitsStub):
76 tt = MyTT
76 tt = MyTT
77
77
78 a = A()
78 a = A()
79 a.tt = 10
79 a.tt = 10
80 self.assertEquals(a.tt, -1)
80 self.assertEquals(a.tt, -1)
81
81
82 def test_default_validate(self):
82 def test_default_validate(self):
83 class MyIntTT(TraitType):
83 class MyIntTT(TraitType):
84 def validate(self, obj, value):
84 def validate(self, obj, value):
85 if isinstance(value, int):
85 if isinstance(value, int):
86 return value
86 return value
87 self.error(obj, value)
87 self.error(obj, value)
88 class A(HasTraits):
88 class A(HasTraits):
89 tt = MyIntTT(10)
89 tt = MyIntTT(10)
90 a = A()
90 a = A()
91 self.assertEquals(a.tt, 10)
91 self.assertEquals(a.tt, 10)
92
92
93 # Defaults are validated when the HasTraits is instantiated
93 # Defaults are validated when the HasTraits is instantiated
94 class B(HasTraits):
94 class B(HasTraits):
95 tt = MyIntTT('bad default')
95 tt = MyIntTT('bad default')
96 self.assertRaises(TraitError, B)
96 self.assertRaises(TraitError, B)
97
97
98 def test_is_valid_for(self):
98 def test_is_valid_for(self):
99 class MyTT(TraitType):
99 class MyTT(TraitType):
100 def is_valid_for(self, value):
100 def is_valid_for(self, value):
101 return True
101 return True
102 class A(HasTraits):
102 class A(HasTraits):
103 tt = MyTT
103 tt = MyTT
104
104
105 a = A()
105 a = A()
106 a.tt = 10
106 a.tt = 10
107 self.assertEquals(a.tt, 10)
107 self.assertEquals(a.tt, 10)
108
108
109 def test_value_for(self):
109 def test_value_for(self):
110 class MyTT(TraitType):
110 class MyTT(TraitType):
111 def value_for(self, value):
111 def value_for(self, value):
112 return 20
112 return 20
113 class A(HasTraits):
113 class A(HasTraits):
114 tt = MyTT
114 tt = MyTT
115
115
116 a = A()
116 a = A()
117 a.tt = 10
117 a.tt = 10
118 self.assertEquals(a.tt, 20)
118 self.assertEquals(a.tt, 20)
119
119
120 def test_info(self):
120 def test_info(self):
121 class A(HasTraits):
121 class A(HasTraits):
122 tt = TraitType
122 tt = TraitType
123 a = A()
123 a = A()
124 self.assertEquals(A.tt.info(), 'any value')
124 self.assertEquals(A.tt.info(), 'any value')
125
125
126 def test_error(self):
126 def test_error(self):
127 class A(HasTraits):
127 class A(HasTraits):
128 tt = TraitType
128 tt = TraitType
129 a = A()
129 a = A()
130 self.assertRaises(TraitError, A.tt.error, a, 10)
130 self.assertRaises(TraitError, A.tt.error, a, 10)
131
131
132 def test_dynamic_initializer(self):
132 def test_dynamic_initializer(self):
133 class A(HasTraits):
133 class A(HasTraits):
134 x = Int(10)
134 x = Int(10)
135 def _x_default(self):
135 def _x_default(self):
136 return 11
136 return 11
137 class B(A):
137 class B(A):
138 x = Int(20)
138 x = Int(20)
139 class C(A):
139 class C(A):
140 def _x_default(self):
140 def _x_default(self):
141 return 21
141 return 21
142
142
143 a = A()
143 a = A()
144 self.assertEquals(a._trait_values, {})
144 self.assertEquals(a._trait_values, {})
145 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
145 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
146 self.assertEquals(a.x, 11)
146 self.assertEquals(a.x, 11)
147 self.assertEquals(a._trait_values, {'x': 11})
147 self.assertEquals(a._trait_values, {'x': 11})
148 b = B()
148 b = B()
149 self.assertEquals(b._trait_values, {'x': 20})
149 self.assertEquals(b._trait_values, {'x': 20})
150 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
150 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
151 self.assertEquals(b.x, 20)
151 self.assertEquals(b.x, 20)
152 c = C()
152 c = C()
153 self.assertEquals(c._trait_values, {})
153 self.assertEquals(c._trait_values, {})
154 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
154 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
155 self.assertEquals(c.x, 21)
155 self.assertEquals(c.x, 21)
156 self.assertEquals(c._trait_values, {'x': 21})
156 self.assertEquals(c._trait_values, {'x': 21})
157 # Ensure that the base class remains unmolested when the _default
157 # Ensure that the base class remains unmolested when the _default
158 # initializer gets overridden in a subclass.
158 # initializer gets overridden in a subclass.
159 a = A()
159 a = A()
160 c = C()
160 c = C()
161 self.assertEquals(a._trait_values, {})
161 self.assertEquals(a._trait_values, {})
162 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
162 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
163 self.assertEquals(a.x, 11)
163 self.assertEquals(a.x, 11)
164 self.assertEquals(a._trait_values, {'x': 11})
164 self.assertEquals(a._trait_values, {'x': 11})
165
165
166
166
167
167
168 class TestHasTraitsMeta(TestCase):
168 class TestHasTraitsMeta(TestCase):
169
169
170 def test_metaclass(self):
170 def test_metaclass(self):
171 self.assertEquals(type(HasTraits), MetaHasTraits)
171 self.assertEquals(type(HasTraits), MetaHasTraits)
172
172
173 class A(HasTraits):
173 class A(HasTraits):
174 a = Int
174 a = Int
175
175
176 a = A()
176 a = A()
177 self.assertEquals(type(a.__class__), MetaHasTraits)
177 self.assertEquals(type(a.__class__), MetaHasTraits)
178 self.assertEquals(a.a,0)
178 self.assertEquals(a.a,0)
179 a.a = 10
179 a.a = 10
180 self.assertEquals(a.a,10)
180 self.assertEquals(a.a,10)
181
181
182 class B(HasTraits):
182 class B(HasTraits):
183 b = Int()
183 b = Int()
184
184
185 b = B()
185 b = B()
186 self.assertEquals(b.b,0)
186 self.assertEquals(b.b,0)
187 b.b = 10
187 b.b = 10
188 self.assertEquals(b.b,10)
188 self.assertEquals(b.b,10)
189
189
190 class C(HasTraits):
190 class C(HasTraits):
191 c = Int(30)
191 c = Int(30)
192
192
193 c = C()
193 c = C()
194 self.assertEquals(c.c,30)
194 self.assertEquals(c.c,30)
195 c.c = 10
195 c.c = 10
196 self.assertEquals(c.c,10)
196 self.assertEquals(c.c,10)
197
197
198 def test_this_class(self):
198 def test_this_class(self):
199 class A(HasTraits):
199 class A(HasTraits):
200 t = This()
200 t = This()
201 tt = This()
201 tt = This()
202 class B(A):
202 class B(A):
203 tt = This()
203 tt = This()
204 ttt = This()
204 ttt = This()
205 self.assertEquals(A.t.this_class, A)
205 self.assertEquals(A.t.this_class, A)
206 self.assertEquals(B.t.this_class, A)
206 self.assertEquals(B.t.this_class, A)
207 self.assertEquals(B.tt.this_class, B)
207 self.assertEquals(B.tt.this_class, B)
208 self.assertEquals(B.ttt.this_class, B)
208 self.assertEquals(B.ttt.this_class, B)
209
209
210 class TestHasTraitsNotify(TestCase):
210 class TestHasTraitsNotify(TestCase):
211
211
212 def setUp(self):
212 def setUp(self):
213 self._notify1 = []
213 self._notify1 = []
214 self._notify2 = []
214 self._notify2 = []
215
215
216 def notify1(self, name, old, new):
216 def notify1(self, name, old, new):
217 self._notify1.append((name, old, new))
217 self._notify1.append((name, old, new))
218
218
219 def notify2(self, name, old, new):
219 def notify2(self, name, old, new):
220 self._notify2.append((name, old, new))
220 self._notify2.append((name, old, new))
221
221
222 def test_notify_all(self):
222 def test_notify_all(self):
223
223
224 class A(HasTraits):
224 class A(HasTraits):
225 a = Int
225 a = Int
226 b = Float
226 b = Float
227
227
228 a = A()
228 a = A()
229 a.on_trait_change(self.notify1)
229 a.on_trait_change(self.notify1)
230 a.a = 0
230 a.a = 0
231 self.assertEquals(len(self._notify1),0)
231 self.assertEquals(len(self._notify1),0)
232 a.b = 0.0
232 a.b = 0.0
233 self.assertEquals(len(self._notify1),0)
233 self.assertEquals(len(self._notify1),0)
234 a.a = 10
234 a.a = 10
235 self.assert_(('a',0,10) in self._notify1)
235 self.assert_(('a',0,10) in self._notify1)
236 a.b = 10.0
236 a.b = 10.0
237 self.assert_(('b',0.0,10.0) in self._notify1)
237 self.assert_(('b',0.0,10.0) in self._notify1)
238 self.assertRaises(TraitError,setattr,a,'a','bad string')
238 self.assertRaises(TraitError,setattr,a,'a','bad string')
239 self.assertRaises(TraitError,setattr,a,'b','bad string')
239 self.assertRaises(TraitError,setattr,a,'b','bad string')
240 self._notify1 = []
240 self._notify1 = []
241 a.on_trait_change(self.notify1,remove=True)
241 a.on_trait_change(self.notify1,remove=True)
242 a.a = 20
242 a.a = 20
243 a.b = 20.0
243 a.b = 20.0
244 self.assertEquals(len(self._notify1),0)
244 self.assertEquals(len(self._notify1),0)
245
245
246 def test_notify_one(self):
246 def test_notify_one(self):
247
247
248 class A(HasTraits):
248 class A(HasTraits):
249 a = Int
249 a = Int
250 b = Float
250 b = Float
251
251
252 a = A()
252 a = A()
253 a.on_trait_change(self.notify1, 'a')
253 a.on_trait_change(self.notify1, 'a')
254 a.a = 0
254 a.a = 0
255 self.assertEquals(len(self._notify1),0)
255 self.assertEquals(len(self._notify1),0)
256 a.a = 10
256 a.a = 10
257 self.assert_(('a',0,10) in self._notify1)
257 self.assert_(('a',0,10) in self._notify1)
258 self.assertRaises(TraitError,setattr,a,'a','bad string')
258 self.assertRaises(TraitError,setattr,a,'a','bad string')
259
259
260 def test_subclass(self):
260 def test_subclass(self):
261
261
262 class A(HasTraits):
262 class A(HasTraits):
263 a = Int
263 a = Int
264
264
265 class B(A):
265 class B(A):
266 b = Float
266 b = Float
267
267
268 b = B()
268 b = B()
269 self.assertEquals(b.a,0)
269 self.assertEquals(b.a,0)
270 self.assertEquals(b.b,0.0)
270 self.assertEquals(b.b,0.0)
271 b.a = 100
271 b.a = 100
272 b.b = 100.0
272 b.b = 100.0
273 self.assertEquals(b.a,100)
273 self.assertEquals(b.a,100)
274 self.assertEquals(b.b,100.0)
274 self.assertEquals(b.b,100.0)
275
275
276 def test_notify_subclass(self):
276 def test_notify_subclass(self):
277
277
278 class A(HasTraits):
278 class A(HasTraits):
279 a = Int
279 a = Int
280
280
281 class B(A):
281 class B(A):
282 b = Float
282 b = Float
283
283
284 b = B()
284 b = B()
285 b.on_trait_change(self.notify1, 'a')
285 b.on_trait_change(self.notify1, 'a')
286 b.on_trait_change(self.notify2, 'b')
286 b.on_trait_change(self.notify2, 'b')
287 b.a = 0
287 b.a = 0
288 b.b = 0.0
288 b.b = 0.0
289 self.assertEquals(len(self._notify1),0)
289 self.assertEquals(len(self._notify1),0)
290 self.assertEquals(len(self._notify2),0)
290 self.assertEquals(len(self._notify2),0)
291 b.a = 10
291 b.a = 10
292 b.b = 10.0
292 b.b = 10.0
293 self.assert_(('a',0,10) in self._notify1)
293 self.assert_(('a',0,10) in self._notify1)
294 self.assert_(('b',0.0,10.0) in self._notify2)
294 self.assert_(('b',0.0,10.0) in self._notify2)
295
295
296 def test_static_notify(self):
296 def test_static_notify(self):
297
297
298 class A(HasTraits):
298 class A(HasTraits):
299 a = Int
299 a = Int
300 _notify1 = []
300 _notify1 = []
301 def _a_changed(self, name, old, new):
301 def _a_changed(self, name, old, new):
302 self._notify1.append((name, old, new))
302 self._notify1.append((name, old, new))
303
303
304 a = A()
304 a = A()
305 a.a = 0
305 a.a = 0
306 # This is broken!!!
306 # This is broken!!!
307 self.assertEquals(len(a._notify1),0)
307 self.assertEquals(len(a._notify1),0)
308 a.a = 10
308 a.a = 10
309 self.assert_(('a',0,10) in a._notify1)
309 self.assert_(('a',0,10) in a._notify1)
310
310
311 class B(A):
311 class B(A):
312 b = Float
312 b = Float
313 _notify2 = []
313 _notify2 = []
314 def _b_changed(self, name, old, new):
314 def _b_changed(self, name, old, new):
315 self._notify2.append((name, old, new))
315 self._notify2.append((name, old, new))
316
316
317 b = B()
317 b = B()
318 b.a = 10
318 b.a = 10
319 b.b = 10.0
319 b.b = 10.0
320 self.assert_(('a',0,10) in b._notify1)
320 self.assert_(('a',0,10) in b._notify1)
321 self.assert_(('b',0.0,10.0) in b._notify2)
321 self.assert_(('b',0.0,10.0) in b._notify2)
322
322
323 def test_notify_args(self):
323 def test_notify_args(self):
324
324
325 def callback0():
325 def callback0():
326 self.cb = ()
326 self.cb = ()
327 def callback1(name):
327 def callback1(name):
328 self.cb = (name,)
328 self.cb = (name,)
329 def callback2(name, new):
329 def callback2(name, new):
330 self.cb = (name, new)
330 self.cb = (name, new)
331 def callback3(name, old, new):
331 def callback3(name, old, new):
332 self.cb = (name, old, new)
332 self.cb = (name, old, new)
333
333
334 class A(HasTraits):
334 class A(HasTraits):
335 a = Int
335 a = Int
336
336
337 a = A()
337 a = A()
338 a.on_trait_change(callback0, 'a')
338 a.on_trait_change(callback0, 'a')
339 a.a = 10
339 a.a = 10
340 self.assertEquals(self.cb,())
340 self.assertEquals(self.cb,())
341 a.on_trait_change(callback0, 'a', remove=True)
341 a.on_trait_change(callback0, 'a', remove=True)
342
342
343 a.on_trait_change(callback1, 'a')
343 a.on_trait_change(callback1, 'a')
344 a.a = 100
344 a.a = 100
345 self.assertEquals(self.cb,('a',))
345 self.assertEquals(self.cb,('a',))
346 a.on_trait_change(callback1, 'a', remove=True)
346 a.on_trait_change(callback1, 'a', remove=True)
347
347
348 a.on_trait_change(callback2, 'a')
348 a.on_trait_change(callback2, 'a')
349 a.a = 1000
349 a.a = 1000
350 self.assertEquals(self.cb,('a',1000))
350 self.assertEquals(self.cb,('a',1000))
351 a.on_trait_change(callback2, 'a', remove=True)
351 a.on_trait_change(callback2, 'a', remove=True)
352
352
353 a.on_trait_change(callback3, 'a')
353 a.on_trait_change(callback3, 'a')
354 a.a = 10000
354 a.a = 10000
355 self.assertEquals(self.cb,('a',1000,10000))
355 self.assertEquals(self.cb,('a',1000,10000))
356 a.on_trait_change(callback3, 'a', remove=True)
356 a.on_trait_change(callback3, 'a', remove=True)
357
357
358 self.assertEquals(len(a._trait_notifiers['a']),0)
358 self.assertEquals(len(a._trait_notifiers['a']),0)
359
359
360
360
361 class TestHasTraits(TestCase):
361 class TestHasTraits(TestCase):
362
362
363 def test_trait_names(self):
363 def test_trait_names(self):
364 class A(HasTraits):
364 class A(HasTraits):
365 i = Int
365 i = Int
366 f = Float
366 f = Float
367 a = A()
367 a = A()
368 self.assertEquals(a.trait_names(),['i','f'])
368 self.assertEquals(a.trait_names(),['i','f'])
369 self.assertEquals(A.class_trait_names(),['i','f'])
369
370
370 def test_trait_metadata(self):
371 def test_trait_metadata(self):
371 class A(HasTraits):
372 class A(HasTraits):
372 i = Int(config_key='MY_VALUE')
373 i = Int(config_key='MY_VALUE')
373 a = A()
374 a = A()
374 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
375 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
375
376
376 def test_traits(self):
377 def test_traits(self):
377 class A(HasTraits):
378 class A(HasTraits):
378 i = Int
379 i = Int
379 f = Float
380 f = Float
380 a = A()
381 a = A()
381 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
382 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
383 self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f))
382
384
383 def test_traits_metadata(self):
385 def test_traits_metadata(self):
384 class A(HasTraits):
386 class A(HasTraits):
385 i = Int(config_key='VALUE1', other_thing='VALUE2')
387 i = Int(config_key='VALUE1', other_thing='VALUE2')
386 f = Float(config_key='VALUE3', other_thing='VALUE2')
388 f = Float(config_key='VALUE3', other_thing='VALUE2')
387 j = Int(0)
389 j = Int(0)
388 a = A()
390 a = A()
389 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
391 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
390 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
392 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
391 self.assertEquals(traits, dict(i=A.i))
393 self.assertEquals(traits, dict(i=A.i))
392
394
393 # This passes, but it shouldn't because I am replicating a bug in
395 # This passes, but it shouldn't because I am replicating a bug in
394 # traits.
396 # traits.
395 traits = a.traits(config_key=lambda v: True)
397 traits = a.traits(config_key=lambda v: True)
396 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
398 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
397
399
398 def test_init(self):
400 def test_init(self):
399 class A(HasTraits):
401 class A(HasTraits):
400 i = Int()
402 i = Int()
401 x = Float()
403 x = Float()
402 a = A(i=1, x=10.0)
404 a = A(i=1, x=10.0)
403 self.assertEquals(a.i, 1)
405 self.assertEquals(a.i, 1)
404 self.assertEquals(a.x, 10.0)
406 self.assertEquals(a.x, 10.0)
405
407
406 #-----------------------------------------------------------------------------
408 #-----------------------------------------------------------------------------
407 # Tests for specific trait types
409 # Tests for specific trait types
408 #-----------------------------------------------------------------------------
410 #-----------------------------------------------------------------------------
409
411
410
412
411 class TestType(TestCase):
413 class TestType(TestCase):
412
414
413 def test_default(self):
415 def test_default(self):
414
416
415 class B(object): pass
417 class B(object): pass
416 class A(HasTraits):
418 class A(HasTraits):
417 klass = Type
419 klass = Type
418
420
419 a = A()
421 a = A()
420 self.assertEquals(a.klass, None)
422 self.assertEquals(a.klass, None)
421
423
422 a.klass = B
424 a.klass = B
423 self.assertEquals(a.klass, B)
425 self.assertEquals(a.klass, B)
424 self.assertRaises(TraitError, setattr, a, 'klass', 10)
426 self.assertRaises(TraitError, setattr, a, 'klass', 10)
425
427
426 def test_value(self):
428 def test_value(self):
427
429
428 class B(object): pass
430 class B(object): pass
429 class C(object): pass
431 class C(object): pass
430 class A(HasTraits):
432 class A(HasTraits):
431 klass = Type(B)
433 klass = Type(B)
432
434
433 a = A()
435 a = A()
434 self.assertEquals(a.klass, B)
436 self.assertEquals(a.klass, B)
435 self.assertRaises(TraitError, setattr, a, 'klass', C)
437 self.assertRaises(TraitError, setattr, a, 'klass', C)
436 self.assertRaises(TraitError, setattr, a, 'klass', object)
438 self.assertRaises(TraitError, setattr, a, 'klass', object)
437 a.klass = B
439 a.klass = B
438
440
439 def test_allow_none(self):
441 def test_allow_none(self):
440
442
441 class B(object): pass
443 class B(object): pass
442 class C(B): pass
444 class C(B): pass
443 class A(HasTraits):
445 class A(HasTraits):
444 klass = Type(B, allow_none=False)
446 klass = Type(B, allow_none=False)
445
447
446 a = A()
448 a = A()
447 self.assertEquals(a.klass, B)
449 self.assertEquals(a.klass, B)
448 self.assertRaises(TraitError, setattr, a, 'klass', None)
450 self.assertRaises(TraitError, setattr, a, 'klass', None)
449 a.klass = C
451 a.klass = C
450 self.assertEquals(a.klass, C)
452 self.assertEquals(a.klass, C)
451
453
452 def test_validate_klass(self):
454 def test_validate_klass(self):
453
455
454 class A(HasTraits):
456 class A(HasTraits):
455 klass = Type('no strings allowed')
457 klass = Type('no strings allowed')
456
458
457 self.assertRaises(ImportError, A)
459 self.assertRaises(ImportError, A)
458
460
459 class A(HasTraits):
461 class A(HasTraits):
460 klass = Type('rub.adub.Duck')
462 klass = Type('rub.adub.Duck')
461
463
462 self.assertRaises(ImportError, A)
464 self.assertRaises(ImportError, A)
463
465
464 def test_validate_default(self):
466 def test_validate_default(self):
465
467
466 class B(object): pass
468 class B(object): pass
467 class A(HasTraits):
469 class A(HasTraits):
468 klass = Type('bad default', B)
470 klass = Type('bad default', B)
469
471
470 self.assertRaises(ImportError, A)
472 self.assertRaises(ImportError, A)
471
473
472 class C(HasTraits):
474 class C(HasTraits):
473 klass = Type(None, B, allow_none=False)
475 klass = Type(None, B, allow_none=False)
474
476
475 self.assertRaises(TraitError, C)
477 self.assertRaises(TraitError, C)
476
478
477 def test_str_klass(self):
479 def test_str_klass(self):
478
480
479 class A(HasTraits):
481 class A(HasTraits):
480 klass = Type('IPython.utils.ipstruct.Struct')
482 klass = Type('IPython.utils.ipstruct.Struct')
481
483
482 from IPython.utils.ipstruct import Struct
484 from IPython.utils.ipstruct import Struct
483 a = A()
485 a = A()
484 a.klass = Struct
486 a.klass = Struct
485 self.assertEquals(a.klass, Struct)
487 self.assertEquals(a.klass, Struct)
486
488
487 self.assertRaises(TraitError, setattr, a, 'klass', 10)
489 self.assertRaises(TraitError, setattr, a, 'klass', 10)
488
490
489 class TestInstance(TestCase):
491 class TestInstance(TestCase):
490
492
491 def test_basic(self):
493 def test_basic(self):
492 class Foo(object): pass
494 class Foo(object): pass
493 class Bar(Foo): pass
495 class Bar(Foo): pass
494 class Bah(object): pass
496 class Bah(object): pass
495
497
496 class A(HasTraits):
498 class A(HasTraits):
497 inst = Instance(Foo)
499 inst = Instance(Foo)
498
500
499 a = A()
501 a = A()
500 self.assert_(a.inst is None)
502 self.assert_(a.inst is None)
501 a.inst = Foo()
503 a.inst = Foo()
502 self.assert_(isinstance(a.inst, Foo))
504 self.assert_(isinstance(a.inst, Foo))
503 a.inst = Bar()
505 a.inst = Bar()
504 self.assert_(isinstance(a.inst, Foo))
506 self.assert_(isinstance(a.inst, Foo))
505 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
507 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
506 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
508 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
507 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
509 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
508
510
509 def test_unique_default_value(self):
511 def test_unique_default_value(self):
510 class Foo(object): pass
512 class Foo(object): pass
511 class A(HasTraits):
513 class A(HasTraits):
512 inst = Instance(Foo,(),{})
514 inst = Instance(Foo,(),{})
513
515
514 a = A()
516 a = A()
515 b = A()
517 b = A()
516 self.assert_(a.inst is not b.inst)
518 self.assert_(a.inst is not b.inst)
517
519
518 def test_args_kw(self):
520 def test_args_kw(self):
519 class Foo(object):
521 class Foo(object):
520 def __init__(self, c): self.c = c
522 def __init__(self, c): self.c = c
521 class Bar(object): pass
523 class Bar(object): pass
522 class Bah(object):
524 class Bah(object):
523 def __init__(self, c, d):
525 def __init__(self, c, d):
524 self.c = c; self.d = d
526 self.c = c; self.d = d
525
527
526 class A(HasTraits):
528 class A(HasTraits):
527 inst = Instance(Foo, (10,))
529 inst = Instance(Foo, (10,))
528 a = A()
530 a = A()
529 self.assertEquals(a.inst.c, 10)
531 self.assertEquals(a.inst.c, 10)
530
532
531 class B(HasTraits):
533 class B(HasTraits):
532 inst = Instance(Bah, args=(10,), kw=dict(d=20))
534 inst = Instance(Bah, args=(10,), kw=dict(d=20))
533 b = B()
535 b = B()
534 self.assertEquals(b.inst.c, 10)
536 self.assertEquals(b.inst.c, 10)
535 self.assertEquals(b.inst.d, 20)
537 self.assertEquals(b.inst.d, 20)
536
538
537 class C(HasTraits):
539 class C(HasTraits):
538 inst = Instance(Foo)
540 inst = Instance(Foo)
539 c = C()
541 c = C()
540 self.assert_(c.inst is None)
542 self.assert_(c.inst is None)
541
543
542 def test_bad_default(self):
544 def test_bad_default(self):
543 class Foo(object): pass
545 class Foo(object): pass
544
546
545 class A(HasTraits):
547 class A(HasTraits):
546 inst = Instance(Foo, allow_none=False)
548 inst = Instance(Foo, allow_none=False)
547
549
548 self.assertRaises(TraitError, A)
550 self.assertRaises(TraitError, A)
549
551
550 def test_instance(self):
552 def test_instance(self):
551 class Foo(object): pass
553 class Foo(object): pass
552
554
553 def inner():
555 def inner():
554 class A(HasTraits):
556 class A(HasTraits):
555 inst = Instance(Foo())
557 inst = Instance(Foo())
556
558
557 self.assertRaises(TraitError, inner)
559 self.assertRaises(TraitError, inner)
558
560
559
561
560 class TestThis(TestCase):
562 class TestThis(TestCase):
561
563
562 def test_this_class(self):
564 def test_this_class(self):
563 class Foo(HasTraits):
565 class Foo(HasTraits):
564 this = This
566 this = This
565
567
566 f = Foo()
568 f = Foo()
567 self.assertEquals(f.this, None)
569 self.assertEquals(f.this, None)
568 g = Foo()
570 g = Foo()
569 f.this = g
571 f.this = g
570 self.assertEquals(f.this, g)
572 self.assertEquals(f.this, g)
571 self.assertRaises(TraitError, setattr, f, 'this', 10)
573 self.assertRaises(TraitError, setattr, f, 'this', 10)
572
574
573 def test_this_inst(self):
575 def test_this_inst(self):
574 class Foo(HasTraits):
576 class Foo(HasTraits):
575 this = This()
577 this = This()
576
578
577 f = Foo()
579 f = Foo()
578 f.this = Foo()
580 f.this = Foo()
579 self.assert_(isinstance(f.this, Foo))
581 self.assert_(isinstance(f.this, Foo))
580
582
581 def test_subclass(self):
583 def test_subclass(self):
582 class Foo(HasTraits):
584 class Foo(HasTraits):
583 t = This()
585 t = This()
584 class Bar(Foo):
586 class Bar(Foo):
585 pass
587 pass
586 f = Foo()
588 f = Foo()
587 b = Bar()
589 b = Bar()
588 f.t = b
590 f.t = b
589 b.t = f
591 b.t = f
590 self.assertEquals(f.t, b)
592 self.assertEquals(f.t, b)
591 self.assertEquals(b.t, f)
593 self.assertEquals(b.t, f)
592
594
593 def test_subclass_override(self):
595 def test_subclass_override(self):
594 class Foo(HasTraits):
596 class Foo(HasTraits):
595 t = This()
597 t = This()
596 class Bar(Foo):
598 class Bar(Foo):
597 t = This()
599 t = This()
598 f = Foo()
600 f = Foo()
599 b = Bar()
601 b = Bar()
600 f.t = b
602 f.t = b
601 self.assertEquals(f.t, b)
603 self.assertEquals(f.t, b)
602 self.assertRaises(TraitError, setattr, b, 't', f)
604 self.assertRaises(TraitError, setattr, b, 't', f)
603
605
604 class TraitTestBase(TestCase):
606 class TraitTestBase(TestCase):
605 """A best testing class for basic trait types."""
607 """A best testing class for basic trait types."""
606
608
607 def assign(self, value):
609 def assign(self, value):
608 self.obj.value = value
610 self.obj.value = value
609
611
610 def coerce(self, value):
612 def coerce(self, value):
611 return value
613 return value
612
614
613 def test_good_values(self):
615 def test_good_values(self):
614 if hasattr(self, '_good_values'):
616 if hasattr(self, '_good_values'):
615 for value in self._good_values:
617 for value in self._good_values:
616 self.assign(value)
618 self.assign(value)
617 self.assertEquals(self.obj.value, self.coerce(value))
619 self.assertEquals(self.obj.value, self.coerce(value))
618
620
619 def test_bad_values(self):
621 def test_bad_values(self):
620 if hasattr(self, '_bad_values'):
622 if hasattr(self, '_bad_values'):
621 for value in self._bad_values:
623 for value in self._bad_values:
622 self.assertRaises(TraitError, self.assign, value)
624 self.assertRaises(TraitError, self.assign, value)
623
625
624 def test_default_value(self):
626 def test_default_value(self):
625 if hasattr(self, '_default_value'):
627 if hasattr(self, '_default_value'):
626 self.assertEquals(self._default_value, self.obj.value)
628 self.assertEquals(self._default_value, self.obj.value)
627
629
628
630
629 class AnyTrait(HasTraits):
631 class AnyTrait(HasTraits):
630
632
631 value = Any
633 value = Any
632
634
633 class AnyTraitTest(TraitTestBase):
635 class AnyTraitTest(TraitTestBase):
634
636
635 obj = AnyTrait()
637 obj = AnyTrait()
636
638
637 _default_value = None
639 _default_value = None
638 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
640 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
639 _bad_values = []
641 _bad_values = []
640
642
641
643
642 class IntTrait(HasTraits):
644 class IntTrait(HasTraits):
643
645
644 value = Int(99)
646 value = Int(99)
645
647
646 class TestInt(TraitTestBase):
648 class TestInt(TraitTestBase):
647
649
648 obj = IntTrait()
650 obj = IntTrait()
649 _default_value = 99
651 _default_value = 99
650 _good_values = [10, -10]
652 _good_values = [10, -10]
651 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j, 10L,
653 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j, 10L,
652 -10L, 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
654 -10L, 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
653 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
655 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
654
656
655
657
656 class LongTrait(HasTraits):
658 class LongTrait(HasTraits):
657
659
658 value = Long(99L)
660 value = Long(99L)
659
661
660 class TestLong(TraitTestBase):
662 class TestLong(TraitTestBase):
661
663
662 obj = LongTrait()
664 obj = LongTrait()
663
665
664 _default_value = 99L
666 _default_value = 99L
665 _good_values = [10, -10, 10L, -10L]
667 _good_values = [10, -10, 10L, -10L]
666 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
668 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
667 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
669 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
668 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
670 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
669 u'-10.1']
671 u'-10.1']
670
672
671
673
672 class FloatTrait(HasTraits):
674 class FloatTrait(HasTraits):
673
675
674 value = Float(99.0)
676 value = Float(99.0)
675
677
676 class TestFloat(TraitTestBase):
678 class TestFloat(TraitTestBase):
677
679
678 obj = FloatTrait()
680 obj = FloatTrait()
679
681
680 _default_value = 99.0
682 _default_value = 99.0
681 _good_values = [10, -10, 10.1, -10.1]
683 _good_values = [10, -10, 10.1, -10.1]
682 _bad_values = [10L, -10L, 'ten', u'ten', [10], {'ten': 10},(10,), None,
684 _bad_values = [10L, -10L, 'ten', u'ten', [10], {'ten': 10},(10,), None,
683 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
685 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
684 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
686 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
685
687
686
688
687 class ComplexTrait(HasTraits):
689 class ComplexTrait(HasTraits):
688
690
689 value = Complex(99.0-99.0j)
691 value = Complex(99.0-99.0j)
690
692
691 class TestComplex(TraitTestBase):
693 class TestComplex(TraitTestBase):
692
694
693 obj = ComplexTrait()
695 obj = ComplexTrait()
694
696
695 _default_value = 99.0-99.0j
697 _default_value = 99.0-99.0j
696 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
698 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
697 10.1j, 10.1+10.1j, 10.1-10.1j]
699 10.1j, 10.1+10.1j, 10.1-10.1j]
698 _bad_values = [10L, -10L, u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
700 _bad_values = [10L, -10L, u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
699
701
700
702
701 class StringTrait(HasTraits):
703 class StringTrait(HasTraits):
702
704
703 value = Str('string')
705 value = Str('string')
704
706
705 class TestString(TraitTestBase):
707 class TestString(TraitTestBase):
706
708
707 obj = StringTrait()
709 obj = StringTrait()
708
710
709 _default_value = 'string'
711 _default_value = 'string'
710 _good_values = ['10', '-10', '10L',
712 _good_values = ['10', '-10', '10L',
711 '-10L', '10.1', '-10.1', 'string']
713 '-10L', '10.1', '-10.1', 'string']
712 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
714 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
713 ['ten'],{'ten': 10},(10,), None, u'string']
715 ['ten'],{'ten': 10},(10,), None, u'string']
714
716
715
717
716 class UnicodeTrait(HasTraits):
718 class UnicodeTrait(HasTraits):
717
719
718 value = Unicode(u'unicode')
720 value = Unicode(u'unicode')
719
721
720 class TestUnicode(TraitTestBase):
722 class TestUnicode(TraitTestBase):
721
723
722 obj = UnicodeTrait()
724 obj = UnicodeTrait()
723
725
724 _default_value = u'unicode'
726 _default_value = u'unicode'
725 _good_values = ['10', '-10', '10L', '-10L', '10.1',
727 _good_values = ['10', '-10', '10L', '-10L', '10.1',
726 '-10.1', '', u'', 'string', u'string', ]
728 '-10.1', '', u'', 'string', u'string', ]
727 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
729 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
728 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
730 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
729
731
730
732
731 class TCPAddressTrait(HasTraits):
733 class TCPAddressTrait(HasTraits):
732
734
733 value = TCPAddress()
735 value = TCPAddress()
734
736
735 class TestTCPAddress(TraitTestBase):
737 class TestTCPAddress(TraitTestBase):
736
738
737 obj = TCPAddressTrait()
739 obj = TCPAddressTrait()
738
740
739 _default_value = ('127.0.0.1',0)
741 _default_value = ('127.0.0.1',0)
740 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
742 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
741 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
743 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
@@ -1,1095 +1,1137 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 from .importstring import import_item
59 from .importstring import import_item
60
60
61 ClassTypes = (ClassType, type)
61 ClassTypes = (ClassType, type)
62
62
63 SequenceTypes = (ListType, TupleType, set, frozenset)
63 SequenceTypes = (ListType, TupleType, set, frozenset)
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Basic classes
66 # Basic classes
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69
69
70 class NoDefaultSpecified ( object ): pass
70 class NoDefaultSpecified ( object ): pass
71 NoDefaultSpecified = NoDefaultSpecified()
71 NoDefaultSpecified = NoDefaultSpecified()
72
72
73
73
74 class Undefined ( object ): pass
74 class Undefined ( object ): pass
75 Undefined = Undefined()
75 Undefined = Undefined()
76
76
77 class TraitError(Exception):
77 class TraitError(Exception):
78 pass
78 pass
79
79
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Utilities
81 # Utilities
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84
84
85 def class_of ( object ):
85 def class_of ( object ):
86 """ Returns a string containing the class name of an object with the
86 """ Returns a string containing the class name of an object with the
87 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
87 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
88 'a PlotValue').
88 'a PlotValue').
89 """
89 """
90 if isinstance( object, basestring ):
90 if isinstance( object, basestring ):
91 return add_article( object )
91 return add_article( object )
92
92
93 return add_article( object.__class__.__name__ )
93 return add_article( object.__class__.__name__ )
94
94
95
95
96 def add_article ( name ):
96 def add_article ( name ):
97 """ Returns a string containing the correct indefinite article ('a' or 'an')
97 """ Returns a string containing the correct indefinite article ('a' or 'an')
98 prefixed to the specified string.
98 prefixed to the specified string.
99 """
99 """
100 if name[:1].lower() in 'aeiou':
100 if name[:1].lower() in 'aeiou':
101 return 'an ' + name
101 return 'an ' + name
102
102
103 return 'a ' + name
103 return 'a ' + name
104
104
105
105
106 def repr_type(obj):
106 def repr_type(obj):
107 """ Return a string representation of a value and its type for readable
107 """ Return a string representation of a value and its type for readable
108 error messages.
108 error messages.
109 """
109 """
110 the_type = type(obj)
110 the_type = type(obj)
111 if the_type is InstanceType:
111 if the_type is InstanceType:
112 # Old-style class.
112 # Old-style class.
113 the_type = obj.__class__
113 the_type = obj.__class__
114 msg = '%r %r' % (obj, the_type)
114 msg = '%r %r' % (obj, the_type)
115 return msg
115 return msg
116
116
117
117
118 def parse_notifier_name(name):
118 def parse_notifier_name(name):
119 """Convert the name argument to a list of names.
119 """Convert the name argument to a list of names.
120
120
121 Examples
121 Examples
122 --------
122 --------
123
123
124 >>> parse_notifier_name('a')
124 >>> parse_notifier_name('a')
125 ['a']
125 ['a']
126 >>> parse_notifier_name(['a','b'])
126 >>> parse_notifier_name(['a','b'])
127 ['a', 'b']
127 ['a', 'b']
128 >>> parse_notifier_name(None)
128 >>> parse_notifier_name(None)
129 ['anytrait']
129 ['anytrait']
130 """
130 """
131 if isinstance(name, str):
131 if isinstance(name, str):
132 return [name]
132 return [name]
133 elif name is None:
133 elif name is None:
134 return ['anytrait']
134 return ['anytrait']
135 elif isinstance(name, (list, tuple)):
135 elif isinstance(name, (list, tuple)):
136 for n in name:
136 for n in name:
137 assert isinstance(n, str), "names must be strings"
137 assert isinstance(n, str), "names must be strings"
138 return name
138 return name
139
139
140
140
141 class _SimpleTest:
141 class _SimpleTest:
142 def __init__ ( self, value ): self.value = value
142 def __init__ ( self, value ): self.value = value
143 def __call__ ( self, test ):
143 def __call__ ( self, test ):
144 return test == self.value
144 return test == self.value
145 def __repr__(self):
145 def __repr__(self):
146 return "<SimpleTest(%r)" % self.value
146 return "<SimpleTest(%r)" % self.value
147 def __str__(self):
147 def __str__(self):
148 return self.__repr__()
148 return self.__repr__()
149
149
150
150
151 def getmembers(object, predicate=None):
151 def getmembers(object, predicate=None):
152 """A safe version of inspect.getmembers that handles missing attributes.
152 """A safe version of inspect.getmembers that handles missing attributes.
153
153
154 This is useful when there are descriptor based attributes that for
154 This is useful when there are descriptor based attributes that for
155 some reason raise AttributeError even though they exist. This happens
155 some reason raise AttributeError even though they exist. This happens
156 in zope.inteface with the __provides__ attribute.
156 in zope.inteface with the __provides__ attribute.
157 """
157 """
158 results = []
158 results = []
159 for key in dir(object):
159 for key in dir(object):
160 try:
160 try:
161 value = getattr(object, key)
161 value = getattr(object, key)
162 except AttributeError:
162 except AttributeError:
163 pass
163 pass
164 else:
164 else:
165 if not predicate or predicate(value):
165 if not predicate or predicate(value):
166 results.append((key, value))
166 results.append((key, value))
167 results.sort()
167 results.sort()
168 return results
168 return results
169
169
170
170
171 #-----------------------------------------------------------------------------
171 #-----------------------------------------------------------------------------
172 # Base TraitType for all traits
172 # Base TraitType for all traits
173 #-----------------------------------------------------------------------------
173 #-----------------------------------------------------------------------------
174
174
175
175
176 class TraitType(object):
176 class TraitType(object):
177 """A base class for all trait descriptors.
177 """A base class for all trait descriptors.
178
178
179 Notes
179 Notes
180 -----
180 -----
181 Our implementation of traits is based on Python's descriptor
181 Our implementation of traits is based on Python's descriptor
182 prototol. This class is the base class for all such descriptors. The
182 prototol. This class is the base class for all such descriptors. The
183 only magic we use is a custom metaclass for the main :class:`HasTraits`
183 only magic we use is a custom metaclass for the main :class:`HasTraits`
184 class that does the following:
184 class that does the following:
185
185
186 1. Sets the :attr:`name` attribute of every :class:`TraitType`
186 1. Sets the :attr:`name` attribute of every :class:`TraitType`
187 instance in the class dict to the name of the attribute.
187 instance in the class dict to the name of the attribute.
188 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
188 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
189 instance in the class dict to the *class* that declared the trait.
189 instance in the class dict to the *class* that declared the trait.
190 This is used by the :class:`This` trait to allow subclasses to
190 This is used by the :class:`This` trait to allow subclasses to
191 accept superclasses for :class:`This` values.
191 accept superclasses for :class:`This` values.
192 """
192 """
193
193
194
194
195 metadata = {}
195 metadata = {}
196 default_value = Undefined
196 default_value = Undefined
197 info_text = 'any value'
197 info_text = 'any value'
198
198
199 def __init__(self, default_value=NoDefaultSpecified, **metadata):
199 def __init__(self, default_value=NoDefaultSpecified, **metadata):
200 """Create a TraitType.
200 """Create a TraitType.
201 """
201 """
202 if default_value is not NoDefaultSpecified:
202 if default_value is not NoDefaultSpecified:
203 self.default_value = default_value
203 self.default_value = default_value
204
204
205 if len(metadata) > 0:
205 if len(metadata) > 0:
206 if len(self.metadata) > 0:
206 if len(self.metadata) > 0:
207 self._metadata = self.metadata.copy()
207 self._metadata = self.metadata.copy()
208 self._metadata.update(metadata)
208 self._metadata.update(metadata)
209 else:
209 else:
210 self._metadata = metadata
210 self._metadata = metadata
211 else:
211 else:
212 self._metadata = self.metadata
212 self._metadata = self.metadata
213
213
214 self.init()
214 self.init()
215
215
216 def init(self):
216 def init(self):
217 pass
217 pass
218
218
219 def get_default_value(self):
219 def get_default_value(self):
220 """Create a new instance of the default value."""
220 """Create a new instance of the default value."""
221 return self.default_value
221 return self.default_value
222
222
223 def instance_init(self, obj):
223 def instance_init(self, obj):
224 """This is called by :meth:`HasTraits.__new__` to finish init'ing.
224 """This is called by :meth:`HasTraits.__new__` to finish init'ing.
225
225
226 Some stages of initialization must be delayed until the parent
226 Some stages of initialization must be delayed until the parent
227 :class:`HasTraits` instance has been created. This method is
227 :class:`HasTraits` instance has been created. This method is
228 called in :meth:`HasTraits.__new__` after the instance has been
228 called in :meth:`HasTraits.__new__` after the instance has been
229 created.
229 created.
230
230
231 This method trigger the creation and validation of default values
231 This method trigger the creation and validation of default values
232 and also things like the resolution of str given class names in
232 and also things like the resolution of str given class names in
233 :class:`Type` and :class`Instance`.
233 :class:`Type` and :class`Instance`.
234
234
235 Parameters
235 Parameters
236 ----------
236 ----------
237 obj : :class:`HasTraits` instance
237 obj : :class:`HasTraits` instance
238 The parent :class:`HasTraits` instance that has just been
238 The parent :class:`HasTraits` instance that has just been
239 created.
239 created.
240 """
240 """
241 self.set_default_value(obj)
241 self.set_default_value(obj)
242
242
243 def set_default_value(self, obj):
243 def set_default_value(self, obj):
244 """Set the default value on a per instance basis.
244 """Set the default value on a per instance basis.
245
245
246 This method is called by :meth:`instance_init` to create and
246 This method is called by :meth:`instance_init` to create and
247 validate the default value. The creation and validation of
247 validate the default value. The creation and validation of
248 default values must be delayed until the parent :class:`HasTraits`
248 default values must be delayed until the parent :class:`HasTraits`
249 class has been instantiated.
249 class has been instantiated.
250 """
250 """
251 # Check for a deferred initializer defined in the same class as the
251 # Check for a deferred initializer defined in the same class as the
252 # trait declaration or above.
252 # trait declaration or above.
253 mro = type(obj).mro()
253 mro = type(obj).mro()
254 meth_name = '_%s_default' % self.name
254 meth_name = '_%s_default' % self.name
255 for cls in mro[:mro.index(self.this_class)+1]:
255 for cls in mro[:mro.index(self.this_class)+1]:
256 if meth_name in cls.__dict__:
256 if meth_name in cls.__dict__:
257 break
257 break
258 else:
258 else:
259 # We didn't find one. Do static initialization.
259 # We didn't find one. Do static initialization.
260 dv = self.get_default_value()
260 dv = self.get_default_value()
261 newdv = self._validate(obj, dv)
261 newdv = self._validate(obj, dv)
262 obj._trait_values[self.name] = newdv
262 obj._trait_values[self.name] = newdv
263 return
263 return
264 # Complete the dynamic initialization.
264 # Complete the dynamic initialization.
265 obj._trait_dyn_inits[self.name] = cls.__dict__[meth_name]
265 obj._trait_dyn_inits[self.name] = cls.__dict__[meth_name]
266
266
267 def __get__(self, obj, cls=None):
267 def __get__(self, obj, cls=None):
268 """Get the value of the trait by self.name for the instance.
268 """Get the value of the trait by self.name for the instance.
269
269
270 Default values are instantiated when :meth:`HasTraits.__new__`
270 Default values are instantiated when :meth:`HasTraits.__new__`
271 is called. Thus by the time this method gets called either the
271 is called. Thus by the time this method gets called either the
272 default value or a user defined value (they called :meth:`__set__`)
272 default value or a user defined value (they called :meth:`__set__`)
273 is in the :class:`HasTraits` instance.
273 is in the :class:`HasTraits` instance.
274 """
274 """
275 if obj is None:
275 if obj is None:
276 return self
276 return self
277 else:
277 else:
278 try:
278 try:
279 value = obj._trait_values[self.name]
279 value = obj._trait_values[self.name]
280 except KeyError:
280 except KeyError:
281 # Check for a dynamic initializer.
281 # Check for a dynamic initializer.
282 if self.name in obj._trait_dyn_inits:
282 if self.name in obj._trait_dyn_inits:
283 value = obj._trait_dyn_inits[self.name](obj)
283 value = obj._trait_dyn_inits[self.name](obj)
284 # FIXME: Do we really validate here?
284 # FIXME: Do we really validate here?
285 value = self._validate(obj, value)
285 value = self._validate(obj, value)
286 obj._trait_values[self.name] = value
286 obj._trait_values[self.name] = value
287 return value
287 return value
288 else:
288 else:
289 raise TraitError('Unexpected error in TraitType: '
289 raise TraitError('Unexpected error in TraitType: '
290 'both default value and dynamic initializer are '
290 'both default value and dynamic initializer are '
291 'absent.')
291 'absent.')
292 except Exception:
292 except Exception:
293 # HasTraits should call set_default_value to populate
293 # HasTraits should call set_default_value to populate
294 # this. So this should never be reached.
294 # this. So this should never be reached.
295 raise TraitError('Unexpected error in TraitType: '
295 raise TraitError('Unexpected error in TraitType: '
296 'default value not set properly')
296 'default value not set properly')
297 else:
297 else:
298 return value
298 return value
299
299
300 def __set__(self, obj, value):
300 def __set__(self, obj, value):
301 new_value = self._validate(obj, value)
301 new_value = self._validate(obj, value)
302 old_value = self.__get__(obj)
302 old_value = self.__get__(obj)
303 if old_value != new_value:
303 if old_value != new_value:
304 obj._trait_values[self.name] = new_value
304 obj._trait_values[self.name] = new_value
305 obj._notify_trait(self.name, old_value, new_value)
305 obj._notify_trait(self.name, old_value, new_value)
306
306
307 def _validate(self, obj, value):
307 def _validate(self, obj, value):
308 if hasattr(self, 'validate'):
308 if hasattr(self, 'validate'):
309 return self.validate(obj, value)
309 return self.validate(obj, value)
310 elif hasattr(self, 'is_valid_for'):
310 elif hasattr(self, 'is_valid_for'):
311 valid = self.is_valid_for(value)
311 valid = self.is_valid_for(value)
312 if valid:
312 if valid:
313 return value
313 return value
314 else:
314 else:
315 raise TraitError('invalid value for type: %r' % value)
315 raise TraitError('invalid value for type: %r' % value)
316 elif hasattr(self, 'value_for'):
316 elif hasattr(self, 'value_for'):
317 return self.value_for(value)
317 return self.value_for(value)
318 else:
318 else:
319 return value
319 return value
320
320
321 def info(self):
321 def info(self):
322 return self.info_text
322 return self.info_text
323
323
324 def error(self, obj, value):
324 def error(self, obj, value):
325 if obj is not None:
325 if obj is not None:
326 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
326 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
327 % (self.name, class_of(obj),
327 % (self.name, class_of(obj),
328 self.info(), repr_type(value))
328 self.info(), repr_type(value))
329 else:
329 else:
330 e = "The '%s' trait must be %s, but a value of %r was specified." \
330 e = "The '%s' trait must be %s, but a value of %r was specified." \
331 % (self.name, self.info(), repr_type(value))
331 % (self.name, self.info(), repr_type(value))
332 raise TraitError(e)
332 raise TraitError(e)
333
333
334 def get_metadata(self, key):
334 def get_metadata(self, key):
335 return getattr(self, '_metadata', {}).get(key, None)
335 return getattr(self, '_metadata', {}).get(key, None)
336
336
337 def set_metadata(self, key, value):
337 def set_metadata(self, key, value):
338 getattr(self, '_metadata', {})[key] = value
338 getattr(self, '_metadata', {})[key] = value
339
339
340
340
341 #-----------------------------------------------------------------------------
341 #-----------------------------------------------------------------------------
342 # The HasTraits implementation
342 # The HasTraits implementation
343 #-----------------------------------------------------------------------------
343 #-----------------------------------------------------------------------------
344
344
345
345
346 class MetaHasTraits(type):
346 class MetaHasTraits(type):
347 """A metaclass for HasTraits.
347 """A metaclass for HasTraits.
348
348
349 This metaclass makes sure that any TraitType class attributes are
349 This metaclass makes sure that any TraitType class attributes are
350 instantiated and sets their name attribute.
350 instantiated and sets their name attribute.
351 """
351 """
352
352
353 def __new__(mcls, name, bases, classdict):
353 def __new__(mcls, name, bases, classdict):
354 """Create the HasTraits class.
354 """Create the HasTraits class.
355
355
356 This instantiates all TraitTypes in the class dict and sets their
356 This instantiates all TraitTypes in the class dict and sets their
357 :attr:`name` attribute.
357 :attr:`name` attribute.
358 """
358 """
359 # print "MetaHasTraitlets (mcls, name): ", mcls, name
359 # print "MetaHasTraitlets (mcls, name): ", mcls, name
360 # print "MetaHasTraitlets (bases): ", bases
360 # print "MetaHasTraitlets (bases): ", bases
361 # print "MetaHasTraitlets (classdict): ", classdict
361 # print "MetaHasTraitlets (classdict): ", classdict
362 for k,v in classdict.iteritems():
362 for k,v in classdict.iteritems():
363 if isinstance(v, TraitType):
363 if isinstance(v, TraitType):
364 v.name = k
364 v.name = k
365 elif inspect.isclass(v):
365 elif inspect.isclass(v):
366 if issubclass(v, TraitType):
366 if issubclass(v, TraitType):
367 vinst = v()
367 vinst = v()
368 vinst.name = k
368 vinst.name = k
369 classdict[k] = vinst
369 classdict[k] = vinst
370 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
370 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
371
371
372 def __init__(cls, name, bases, classdict):
372 def __init__(cls, name, bases, classdict):
373 """Finish initializing the HasTraits class.
373 """Finish initializing the HasTraits class.
374
374
375 This sets the :attr:`this_class` attribute of each TraitType in the
375 This sets the :attr:`this_class` attribute of each TraitType in the
376 class dict to the newly created class ``cls``.
376 class dict to the newly created class ``cls``.
377 """
377 """
378 for k, v in classdict.iteritems():
378 for k, v in classdict.iteritems():
379 if isinstance(v, TraitType):
379 if isinstance(v, TraitType):
380 v.this_class = cls
380 v.this_class = cls
381 super(MetaHasTraits, cls).__init__(name, bases, classdict)
381 super(MetaHasTraits, cls).__init__(name, bases, classdict)
382
382
383 class HasTraits(object):
383 class HasTraits(object):
384
384
385 __metaclass__ = MetaHasTraits
385 __metaclass__ = MetaHasTraits
386
386
387 def __new__(cls, **kw):
387 def __new__(cls, **kw):
388 # This is needed because in Python 2.6 object.__new__ only accepts
388 # This is needed because in Python 2.6 object.__new__ only accepts
389 # the cls argument.
389 # the cls argument.
390 new_meth = super(HasTraits, cls).__new__
390 new_meth = super(HasTraits, cls).__new__
391 if new_meth is object.__new__:
391 if new_meth is object.__new__:
392 inst = new_meth(cls)
392 inst = new_meth(cls)
393 else:
393 else:
394 inst = new_meth(cls, **kw)
394 inst = new_meth(cls, **kw)
395 inst._trait_values = {}
395 inst._trait_values = {}
396 inst._trait_notifiers = {}
396 inst._trait_notifiers = {}
397 inst._trait_dyn_inits = {}
397 inst._trait_dyn_inits = {}
398 # Here we tell all the TraitType instances to set their default
398 # Here we tell all the TraitType instances to set their default
399 # values on the instance.
399 # values on the instance.
400 for key in dir(cls):
400 for key in dir(cls):
401 # Some descriptors raise AttributeError like zope.interface's
401 # Some descriptors raise AttributeError like zope.interface's
402 # __provides__ attributes even though they exist. This causes
402 # __provides__ attributes even though they exist. This causes
403 # AttributeErrors even though they are listed in dir(cls).
403 # AttributeErrors even though they are listed in dir(cls).
404 try:
404 try:
405 value = getattr(cls, key)
405 value = getattr(cls, key)
406 except AttributeError:
406 except AttributeError:
407 pass
407 pass
408 else:
408 else:
409 if isinstance(value, TraitType):
409 if isinstance(value, TraitType):
410 value.instance_init(inst)
410 value.instance_init(inst)
411
411
412 return inst
412 return inst
413
413
414 def __init__(self, **kw):
414 def __init__(self, **kw):
415 # Allow trait values to be set using keyword arguments.
415 # Allow trait values to be set using keyword arguments.
416 # We need to use setattr for this to trigger validation and
416 # We need to use setattr for this to trigger validation and
417 # notifications.
417 # notifications.
418 for key, value in kw.iteritems():
418 for key, value in kw.iteritems():
419 setattr(self, key, value)
419 setattr(self, key, value)
420
420
421 def _notify_trait(self, name, old_value, new_value):
421 def _notify_trait(self, name, old_value, new_value):
422
422
423 # First dynamic ones
423 # First dynamic ones
424 callables = self._trait_notifiers.get(name,[])
424 callables = self._trait_notifiers.get(name,[])
425 more_callables = self._trait_notifiers.get('anytrait',[])
425 more_callables = self._trait_notifiers.get('anytrait',[])
426 callables.extend(more_callables)
426 callables.extend(more_callables)
427
427
428 # Now static ones
428 # Now static ones
429 try:
429 try:
430 cb = getattr(self, '_%s_changed' % name)
430 cb = getattr(self, '_%s_changed' % name)
431 except:
431 except:
432 pass
432 pass
433 else:
433 else:
434 callables.append(cb)
434 callables.append(cb)
435
435
436 # Call them all now
436 # Call them all now
437 for c in callables:
437 for c in callables:
438 # Traits catches and logs errors here. I allow them to raise
438 # Traits catches and logs errors here. I allow them to raise
439 if callable(c):
439 if callable(c):
440 argspec = inspect.getargspec(c)
440 argspec = inspect.getargspec(c)
441 nargs = len(argspec[0])
441 nargs = len(argspec[0])
442 # Bound methods have an additional 'self' argument
442 # Bound methods have an additional 'self' argument
443 # I don't know how to treat unbound methods, but they
443 # I don't know how to treat unbound methods, but they
444 # can't really be used for callbacks.
444 # can't really be used for callbacks.
445 if isinstance(c, types.MethodType):
445 if isinstance(c, types.MethodType):
446 offset = -1
446 offset = -1
447 else:
447 else:
448 offset = 0
448 offset = 0
449 if nargs + offset == 0:
449 if nargs + offset == 0:
450 c()
450 c()
451 elif nargs + offset == 1:
451 elif nargs + offset == 1:
452 c(name)
452 c(name)
453 elif nargs + offset == 2:
453 elif nargs + offset == 2:
454 c(name, new_value)
454 c(name, new_value)
455 elif nargs + offset == 3:
455 elif nargs + offset == 3:
456 c(name, old_value, new_value)
456 c(name, old_value, new_value)
457 else:
457 else:
458 raise TraitError('a trait changed callback '
458 raise TraitError('a trait changed callback '
459 'must have 0-3 arguments.')
459 'must have 0-3 arguments.')
460 else:
460 else:
461 raise TraitError('a trait changed callback '
461 raise TraitError('a trait changed callback '
462 'must be callable.')
462 'must be callable.')
463
463
464
464
465 def _add_notifiers(self, handler, name):
465 def _add_notifiers(self, handler, name):
466 if not self._trait_notifiers.has_key(name):
466 if not self._trait_notifiers.has_key(name):
467 nlist = []
467 nlist = []
468 self._trait_notifiers[name] = nlist
468 self._trait_notifiers[name] = nlist
469 else:
469 else:
470 nlist = self._trait_notifiers[name]
470 nlist = self._trait_notifiers[name]
471 if handler not in nlist:
471 if handler not in nlist:
472 nlist.append(handler)
472 nlist.append(handler)
473
473
474 def _remove_notifiers(self, handler, name):
474 def _remove_notifiers(self, handler, name):
475 if self._trait_notifiers.has_key(name):
475 if self._trait_notifiers.has_key(name):
476 nlist = self._trait_notifiers[name]
476 nlist = self._trait_notifiers[name]
477 try:
477 try:
478 index = nlist.index(handler)
478 index = nlist.index(handler)
479 except ValueError:
479 except ValueError:
480 pass
480 pass
481 else:
481 else:
482 del nlist[index]
482 del nlist[index]
483
483
484 def on_trait_change(self, handler, name=None, remove=False):
484 def on_trait_change(self, handler, name=None, remove=False):
485 """Setup a handler to be called when a trait changes.
485 """Setup a handler to be called when a trait changes.
486
486
487 This is used to setup dynamic notifications of trait changes.
487 This is used to setup dynamic notifications of trait changes.
488
488
489 Static handlers can be created by creating methods on a HasTraits
489 Static handlers can be created by creating methods on a HasTraits
490 subclass with the naming convention '_[traitname]_changed'. Thus,
490 subclass with the naming convention '_[traitname]_changed'. Thus,
491 to create static handler for the trait 'a', create the method
491 to create static handler for the trait 'a', create the method
492 _a_changed(self, name, old, new) (fewer arguments can be used, see
492 _a_changed(self, name, old, new) (fewer arguments can be used, see
493 below).
493 below).
494
494
495 Parameters
495 Parameters
496 ----------
496 ----------
497 handler : callable
497 handler : callable
498 A callable that is called when a trait changes. Its
498 A callable that is called when a trait changes. Its
499 signature can be handler(), handler(name), handler(name, new)
499 signature can be handler(), handler(name), handler(name, new)
500 or handler(name, old, new).
500 or handler(name, old, new).
501 name : list, str, None
501 name : list, str, None
502 If None, the handler will apply to all traits. If a list
502 If None, the handler will apply to all traits. If a list
503 of str, handler will apply to all names in the list. If a
503 of str, handler will apply to all names in the list. If a
504 str, the handler will apply just to that name.
504 str, the handler will apply just to that name.
505 remove : bool
505 remove : bool
506 If False (the default), then install the handler. If True
506 If False (the default), then install the handler. If True
507 then unintall it.
507 then unintall it.
508 """
508 """
509 if remove:
509 if remove:
510 names = parse_notifier_name(name)
510 names = parse_notifier_name(name)
511 for n in names:
511 for n in names:
512 self._remove_notifiers(handler, n)
512 self._remove_notifiers(handler, n)
513 else:
513 else:
514 names = parse_notifier_name(name)
514 names = parse_notifier_name(name)
515 for n in names:
515 for n in names:
516 self._add_notifiers(handler, n)
516 self._add_notifiers(handler, n)
517
517
518 @classmethod
519 def class_trait_names(cls, **metadata):
520 """Get a list of all the names of this classes traits.
521
522 This method is just like the :meth:`trait_names` method, but is unbound.
523 """
524 return cls.class_traits(**metadata).keys()
525
526 @classmethod
527 def class_traits(cls, **metadata):
528 """Get a list of all the traits of this class.
529
530 This method is just like the :meth:`traits` method, but is unbound.
531
532 The TraitTypes returned don't know anything about the values
533 that the various HasTrait's instances are holding.
534
535 This follows the same algorithm as traits does and does not allow
536 for any simple way of specifying merely that a metadata name
537 exists, but has any value. This is because get_metadata returns
538 None if a metadata key doesn't exist.
539 """
540 traits = dict([memb for memb in getmembers(cls) if \
541 isinstance(memb[1], TraitType)])
542
543 if len(metadata) == 0:
544 return traits
545
546 for meta_name, meta_eval in metadata.items():
547 if type(meta_eval) is not FunctionType:
548 metadata[meta_name] = _SimpleTest(meta_eval)
549
550 result = {}
551 for name, trait in traits.items():
552 for meta_name, meta_eval in metadata.items():
553 if not meta_eval(trait.get_metadata(meta_name)):
554 break
555 else:
556 result[name] = trait
557
558 return result
559
518 def trait_names(self, **metadata):
560 def trait_names(self, **metadata):
519 """Get a list of all the names of this classes traits."""
561 """Get a list of all the names of this classes traits."""
520 return self.traits(**metadata).keys()
562 return self.traits(**metadata).keys()
521
563
522 def traits(self, **metadata):
564 def traits(self, **metadata):
523 """Get a list of all the traits of this class.
565 """Get a list of all the traits of this class.
524
566
525 The TraitTypes returned don't know anything about the values
567 The TraitTypes returned don't know anything about the values
526 that the various HasTrait's instances are holding.
568 that the various HasTrait's instances are holding.
527
569
528 This follows the same algorithm as traits does and does not allow
570 This follows the same algorithm as traits does and does not allow
529 for any simple way of specifying merely that a metadata name
571 for any simple way of specifying merely that a metadata name
530 exists, but has any value. This is because get_metadata returns
572 exists, but has any value. This is because get_metadata returns
531 None if a metadata key doesn't exist.
573 None if a metadata key doesn't exist.
532 """
574 """
533 traits = dict([memb for memb in getmembers(self.__class__) if \
575 traits = dict([memb for memb in getmembers(self.__class__) if \
534 isinstance(memb[1], TraitType)])
576 isinstance(memb[1], TraitType)])
535
577
536 if len(metadata) == 0:
578 if len(metadata) == 0:
537 return traits
579 return traits
538
580
539 for meta_name, meta_eval in metadata.items():
581 for meta_name, meta_eval in metadata.items():
540 if type(meta_eval) is not FunctionType:
582 if type(meta_eval) is not FunctionType:
541 metadata[meta_name] = _SimpleTest(meta_eval)
583 metadata[meta_name] = _SimpleTest(meta_eval)
542
584
543 result = {}
585 result = {}
544 for name, trait in traits.items():
586 for name, trait in traits.items():
545 for meta_name, meta_eval in metadata.items():
587 for meta_name, meta_eval in metadata.items():
546 if not meta_eval(trait.get_metadata(meta_name)):
588 if not meta_eval(trait.get_metadata(meta_name)):
547 break
589 break
548 else:
590 else:
549 result[name] = trait
591 result[name] = trait
550
592
551 return result
593 return result
552
594
553 def trait_metadata(self, traitname, key):
595 def trait_metadata(self, traitname, key):
554 """Get metadata values for trait by key."""
596 """Get metadata values for trait by key."""
555 try:
597 try:
556 trait = getattr(self.__class__, traitname)
598 trait = getattr(self.__class__, traitname)
557 except AttributeError:
599 except AttributeError:
558 raise TraitError("Class %s does not have a trait named %s" %
600 raise TraitError("Class %s does not have a trait named %s" %
559 (self.__class__.__name__, traitname))
601 (self.__class__.__name__, traitname))
560 else:
602 else:
561 return trait.get_metadata(key)
603 return trait.get_metadata(key)
562
604
563 #-----------------------------------------------------------------------------
605 #-----------------------------------------------------------------------------
564 # Actual TraitTypes implementations/subclasses
606 # Actual TraitTypes implementations/subclasses
565 #-----------------------------------------------------------------------------
607 #-----------------------------------------------------------------------------
566
608
567 #-----------------------------------------------------------------------------
609 #-----------------------------------------------------------------------------
568 # TraitTypes subclasses for handling classes and instances of classes
610 # TraitTypes subclasses for handling classes and instances of classes
569 #-----------------------------------------------------------------------------
611 #-----------------------------------------------------------------------------
570
612
571
613
572 class ClassBasedTraitType(TraitType):
614 class ClassBasedTraitType(TraitType):
573 """A trait with error reporting for Type, Instance and This."""
615 """A trait with error reporting for Type, Instance and This."""
574
616
575 def error(self, obj, value):
617 def error(self, obj, value):
576 kind = type(value)
618 kind = type(value)
577 if kind is InstanceType:
619 if kind is InstanceType:
578 msg = 'class %s' % value.__class__.__name__
620 msg = 'class %s' % value.__class__.__name__
579 else:
621 else:
580 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
622 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
581
623
582 super(ClassBasedTraitType, self).error(obj, msg)
624 super(ClassBasedTraitType, self).error(obj, msg)
583
625
584
626
585 class Type(ClassBasedTraitType):
627 class Type(ClassBasedTraitType):
586 """A trait whose value must be a subclass of a specified class."""
628 """A trait whose value must be a subclass of a specified class."""
587
629
588 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
630 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
589 """Construct a Type trait
631 """Construct a Type trait
590
632
591 A Type trait specifies that its values must be subclasses of
633 A Type trait specifies that its values must be subclasses of
592 a particular class.
634 a particular class.
593
635
594 If only ``default_value`` is given, it is used for the ``klass`` as
636 If only ``default_value`` is given, it is used for the ``klass`` as
595 well.
637 well.
596
638
597 Parameters
639 Parameters
598 ----------
640 ----------
599 default_value : class, str or None
641 default_value : class, str or None
600 The default value must be a subclass of klass. If an str,
642 The default value must be a subclass of klass. If an str,
601 the str must be a fully specified class name, like 'foo.bar.Bah'.
643 the str must be a fully specified class name, like 'foo.bar.Bah'.
602 The string is resolved into real class, when the parent
644 The string is resolved into real class, when the parent
603 :class:`HasTraits` class is instantiated.
645 :class:`HasTraits` class is instantiated.
604 klass : class, str, None
646 klass : class, str, None
605 Values of this trait must be a subclass of klass. The klass
647 Values of this trait must be a subclass of klass. The klass
606 may be specified in a string like: 'foo.bar.MyClass'.
648 may be specified in a string like: 'foo.bar.MyClass'.
607 The string is resolved into real class, when the parent
649 The string is resolved into real class, when the parent
608 :class:`HasTraits` class is instantiated.
650 :class:`HasTraits` class is instantiated.
609 allow_none : boolean
651 allow_none : boolean
610 Indicates whether None is allowed as an assignable value. Even if
652 Indicates whether None is allowed as an assignable value. Even if
611 ``False``, the default value may be ``None``.
653 ``False``, the default value may be ``None``.
612 """
654 """
613 if default_value is None:
655 if default_value is None:
614 if klass is None:
656 if klass is None:
615 klass = object
657 klass = object
616 elif klass is None:
658 elif klass is None:
617 klass = default_value
659 klass = default_value
618
660
619 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
661 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
620 raise TraitError("A Type trait must specify a class.")
662 raise TraitError("A Type trait must specify a class.")
621
663
622 self.klass = klass
664 self.klass = klass
623 self._allow_none = allow_none
665 self._allow_none = allow_none
624
666
625 super(Type, self).__init__(default_value, **metadata)
667 super(Type, self).__init__(default_value, **metadata)
626
668
627 def validate(self, obj, value):
669 def validate(self, obj, value):
628 """Validates that the value is a valid object instance."""
670 """Validates that the value is a valid object instance."""
629 try:
671 try:
630 if issubclass(value, self.klass):
672 if issubclass(value, self.klass):
631 return value
673 return value
632 except:
674 except:
633 if (value is None) and (self._allow_none):
675 if (value is None) and (self._allow_none):
634 return value
676 return value
635
677
636 self.error(obj, value)
678 self.error(obj, value)
637
679
638 def info(self):
680 def info(self):
639 """ Returns a description of the trait."""
681 """ Returns a description of the trait."""
640 if isinstance(self.klass, basestring):
682 if isinstance(self.klass, basestring):
641 klass = self.klass
683 klass = self.klass
642 else:
684 else:
643 klass = self.klass.__name__
685 klass = self.klass.__name__
644 result = 'a subclass of ' + klass
686 result = 'a subclass of ' + klass
645 if self._allow_none:
687 if self._allow_none:
646 return result + ' or None'
688 return result + ' or None'
647 return result
689 return result
648
690
649 def instance_init(self, obj):
691 def instance_init(self, obj):
650 self._resolve_classes()
692 self._resolve_classes()
651 super(Type, self).instance_init(obj)
693 super(Type, self).instance_init(obj)
652
694
653 def _resolve_classes(self):
695 def _resolve_classes(self):
654 if isinstance(self.klass, basestring):
696 if isinstance(self.klass, basestring):
655 self.klass = import_item(self.klass)
697 self.klass = import_item(self.klass)
656 if isinstance(self.default_value, basestring):
698 if isinstance(self.default_value, basestring):
657 self.default_value = import_item(self.default_value)
699 self.default_value = import_item(self.default_value)
658
700
659 def get_default_value(self):
701 def get_default_value(self):
660 return self.default_value
702 return self.default_value
661
703
662
704
663 class DefaultValueGenerator(object):
705 class DefaultValueGenerator(object):
664 """A class for generating new default value instances."""
706 """A class for generating new default value instances."""
665
707
666 def __init__(self, *args, **kw):
708 def __init__(self, *args, **kw):
667 self.args = args
709 self.args = args
668 self.kw = kw
710 self.kw = kw
669
711
670 def generate(self, klass):
712 def generate(self, klass):
671 return klass(*self.args, **self.kw)
713 return klass(*self.args, **self.kw)
672
714
673
715
674 class Instance(ClassBasedTraitType):
716 class Instance(ClassBasedTraitType):
675 """A trait whose value must be an instance of a specified class.
717 """A trait whose value must be an instance of a specified class.
676
718
677 The value can also be an instance of a subclass of the specified class.
719 The value can also be an instance of a subclass of the specified class.
678 """
720 """
679
721
680 def __init__(self, klass=None, args=None, kw=None,
722 def __init__(self, klass=None, args=None, kw=None,
681 allow_none=True, **metadata ):
723 allow_none=True, **metadata ):
682 """Construct an Instance trait.
724 """Construct an Instance trait.
683
725
684 This trait allows values that are instances of a particular
726 This trait allows values that are instances of a particular
685 class or its sublclasses. Our implementation is quite different
727 class or its sublclasses. Our implementation is quite different
686 from that of enthough.traits as we don't allow instances to be used
728 from that of enthough.traits as we don't allow instances to be used
687 for klass and we handle the ``args`` and ``kw`` arguments differently.
729 for klass and we handle the ``args`` and ``kw`` arguments differently.
688
730
689 Parameters
731 Parameters
690 ----------
732 ----------
691 klass : class, str
733 klass : class, str
692 The class that forms the basis for the trait. Class names
734 The class that forms the basis for the trait. Class names
693 can also be specified as strings, like 'foo.bar.Bar'.
735 can also be specified as strings, like 'foo.bar.Bar'.
694 args : tuple
736 args : tuple
695 Positional arguments for generating the default value.
737 Positional arguments for generating the default value.
696 kw : dict
738 kw : dict
697 Keyword arguments for generating the default value.
739 Keyword arguments for generating the default value.
698 allow_none : bool
740 allow_none : bool
699 Indicates whether None is allowed as a value.
741 Indicates whether None is allowed as a value.
700
742
701 Default Value
743 Default Value
702 -------------
744 -------------
703 If both ``args`` and ``kw`` are None, then the default value is None.
745 If both ``args`` and ``kw`` are None, then the default value is None.
704 If ``args`` is a tuple and ``kw`` is a dict, then the default is
746 If ``args`` is a tuple and ``kw`` is a dict, then the default is
705 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
747 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
706 not (but not both), None is replace by ``()`` or ``{}``.
748 not (but not both), None is replace by ``()`` or ``{}``.
707 """
749 """
708
750
709 self._allow_none = allow_none
751 self._allow_none = allow_none
710
752
711 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
753 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
712 raise TraitError('The klass argument must be a class'
754 raise TraitError('The klass argument must be a class'
713 ' you gave: %r' % klass)
755 ' you gave: %r' % klass)
714 self.klass = klass
756 self.klass = klass
715
757
716 # self.klass is a class, so handle default_value
758 # self.klass is a class, so handle default_value
717 if args is None and kw is None:
759 if args is None and kw is None:
718 default_value = None
760 default_value = None
719 else:
761 else:
720 if args is None:
762 if args is None:
721 # kw is not None
763 # kw is not None
722 args = ()
764 args = ()
723 elif kw is None:
765 elif kw is None:
724 # args is not None
766 # args is not None
725 kw = {}
767 kw = {}
726
768
727 if not isinstance(kw, dict):
769 if not isinstance(kw, dict):
728 raise TraitError("The 'kw' argument must be a dict or None.")
770 raise TraitError("The 'kw' argument must be a dict or None.")
729 if not isinstance(args, tuple):
771 if not isinstance(args, tuple):
730 raise TraitError("The 'args' argument must be a tuple or None.")
772 raise TraitError("The 'args' argument must be a tuple or None.")
731
773
732 default_value = DefaultValueGenerator(*args, **kw)
774 default_value = DefaultValueGenerator(*args, **kw)
733
775
734 super(Instance, self).__init__(default_value, **metadata)
776 super(Instance, self).__init__(default_value, **metadata)
735
777
736 def validate(self, obj, value):
778 def validate(self, obj, value):
737 if value is None:
779 if value is None:
738 if self._allow_none:
780 if self._allow_none:
739 return value
781 return value
740 self.error(obj, value)
782 self.error(obj, value)
741
783
742 if isinstance(value, self.klass):
784 if isinstance(value, self.klass):
743 return value
785 return value
744 else:
786 else:
745 self.error(obj, value)
787 self.error(obj, value)
746
788
747 def info(self):
789 def info(self):
748 if isinstance(self.klass, basestring):
790 if isinstance(self.klass, basestring):
749 klass = self.klass
791 klass = self.klass
750 else:
792 else:
751 klass = self.klass.__name__
793 klass = self.klass.__name__
752 result = class_of(klass)
794 result = class_of(klass)
753 if self._allow_none:
795 if self._allow_none:
754 return result + ' or None'
796 return result + ' or None'
755
797
756 return result
798 return result
757
799
758 def instance_init(self, obj):
800 def instance_init(self, obj):
759 self._resolve_classes()
801 self._resolve_classes()
760 super(Instance, self).instance_init(obj)
802 super(Instance, self).instance_init(obj)
761
803
762 def _resolve_classes(self):
804 def _resolve_classes(self):
763 if isinstance(self.klass, basestring):
805 if isinstance(self.klass, basestring):
764 self.klass = import_item(self.klass)
806 self.klass = import_item(self.klass)
765
807
766 def get_default_value(self):
808 def get_default_value(self):
767 """Instantiate a default value instance.
809 """Instantiate a default value instance.
768
810
769 This is called when the containing HasTraits classes'
811 This is called when the containing HasTraits classes'
770 :meth:`__new__` method is called to ensure that a unique instance
812 :meth:`__new__` method is called to ensure that a unique instance
771 is created for each HasTraits instance.
813 is created for each HasTraits instance.
772 """
814 """
773 dv = self.default_value
815 dv = self.default_value
774 if isinstance(dv, DefaultValueGenerator):
816 if isinstance(dv, DefaultValueGenerator):
775 return dv.generate(self.klass)
817 return dv.generate(self.klass)
776 else:
818 else:
777 return dv
819 return dv
778
820
779
821
780 class This(ClassBasedTraitType):
822 class This(ClassBasedTraitType):
781 """A trait for instances of the class containing this trait.
823 """A trait for instances of the class containing this trait.
782
824
783 Because how how and when class bodies are executed, the ``This``
825 Because how how and when class bodies are executed, the ``This``
784 trait can only have a default value of None. This, and because we
826 trait can only have a default value of None. This, and because we
785 always validate default values, ``allow_none`` is *always* true.
827 always validate default values, ``allow_none`` is *always* true.
786 """
828 """
787
829
788 info_text = 'an instance of the same type as the receiver or None'
830 info_text = 'an instance of the same type as the receiver or None'
789
831
790 def __init__(self, **metadata):
832 def __init__(self, **metadata):
791 super(This, self).__init__(None, **metadata)
833 super(This, self).__init__(None, **metadata)
792
834
793 def validate(self, obj, value):
835 def validate(self, obj, value):
794 # What if value is a superclass of obj.__class__? This is
836 # What if value is a superclass of obj.__class__? This is
795 # complicated if it was the superclass that defined the This
837 # complicated if it was the superclass that defined the This
796 # trait.
838 # trait.
797 if isinstance(value, self.this_class) or (value is None):
839 if isinstance(value, self.this_class) or (value is None):
798 return value
840 return value
799 else:
841 else:
800 self.error(obj, value)
842 self.error(obj, value)
801
843
802
844
803 #-----------------------------------------------------------------------------
845 #-----------------------------------------------------------------------------
804 # Basic TraitTypes implementations/subclasses
846 # Basic TraitTypes implementations/subclasses
805 #-----------------------------------------------------------------------------
847 #-----------------------------------------------------------------------------
806
848
807
849
808 class Any(TraitType):
850 class Any(TraitType):
809 default_value = None
851 default_value = None
810 info_text = 'any value'
852 info_text = 'any value'
811
853
812
854
813 class Int(TraitType):
855 class Int(TraitType):
814 """A integer trait."""
856 """A integer trait."""
815
857
816 default_value = 0
858 default_value = 0
817 info_text = 'an integer'
859 info_text = 'an integer'
818
860
819 def validate(self, obj, value):
861 def validate(self, obj, value):
820 if isinstance(value, int):
862 if isinstance(value, int):
821 return value
863 return value
822 self.error(obj, value)
864 self.error(obj, value)
823
865
824 class CInt(Int):
866 class CInt(Int):
825 """A casting version of the int trait."""
867 """A casting version of the int trait."""
826
868
827 def validate(self, obj, value):
869 def validate(self, obj, value):
828 try:
870 try:
829 return int(value)
871 return int(value)
830 except:
872 except:
831 self.error(obj, value)
873 self.error(obj, value)
832
874
833
875
834 class Long(TraitType):
876 class Long(TraitType):
835 """A long integer trait."""
877 """A long integer trait."""
836
878
837 default_value = 0L
879 default_value = 0L
838 info_text = 'a long'
880 info_text = 'a long'
839
881
840 def validate(self, obj, value):
882 def validate(self, obj, value):
841 if isinstance(value, long):
883 if isinstance(value, long):
842 return value
884 return value
843 if isinstance(value, int):
885 if isinstance(value, int):
844 return long(value)
886 return long(value)
845 self.error(obj, value)
887 self.error(obj, value)
846
888
847
889
848 class CLong(Long):
890 class CLong(Long):
849 """A casting version of the long integer trait."""
891 """A casting version of the long integer trait."""
850
892
851 def validate(self, obj, value):
893 def validate(self, obj, value):
852 try:
894 try:
853 return long(value)
895 return long(value)
854 except:
896 except:
855 self.error(obj, value)
897 self.error(obj, value)
856
898
857
899
858 class Float(TraitType):
900 class Float(TraitType):
859 """A float trait."""
901 """A float trait."""
860
902
861 default_value = 0.0
903 default_value = 0.0
862 info_text = 'a float'
904 info_text = 'a float'
863
905
864 def validate(self, obj, value):
906 def validate(self, obj, value):
865 if isinstance(value, float):
907 if isinstance(value, float):
866 return value
908 return value
867 if isinstance(value, int):
909 if isinstance(value, int):
868 return float(value)
910 return float(value)
869 self.error(obj, value)
911 self.error(obj, value)
870
912
871
913
872 class CFloat(Float):
914 class CFloat(Float):
873 """A casting version of the float trait."""
915 """A casting version of the float trait."""
874
916
875 def validate(self, obj, value):
917 def validate(self, obj, value):
876 try:
918 try:
877 return float(value)
919 return float(value)
878 except:
920 except:
879 self.error(obj, value)
921 self.error(obj, value)
880
922
881 class Complex(TraitType):
923 class Complex(TraitType):
882 """A trait for complex numbers."""
924 """A trait for complex numbers."""
883
925
884 default_value = 0.0 + 0.0j
926 default_value = 0.0 + 0.0j
885 info_text = 'a complex number'
927 info_text = 'a complex number'
886
928
887 def validate(self, obj, value):
929 def validate(self, obj, value):
888 if isinstance(value, complex):
930 if isinstance(value, complex):
889 return value
931 return value
890 if isinstance(value, (float, int)):
932 if isinstance(value, (float, int)):
891 return complex(value)
933 return complex(value)
892 self.error(obj, value)
934 self.error(obj, value)
893
935
894
936
895 class CComplex(Complex):
937 class CComplex(Complex):
896 """A casting version of the complex number trait."""
938 """A casting version of the complex number trait."""
897
939
898 def validate (self, obj, value):
940 def validate (self, obj, value):
899 try:
941 try:
900 return complex(value)
942 return complex(value)
901 except:
943 except:
902 self.error(obj, value)
944 self.error(obj, value)
903
945
904
946
905 class Str(TraitType):
947 class Str(TraitType):
906 """A trait for strings."""
948 """A trait for strings."""
907
949
908 default_value = ''
950 default_value = ''
909 info_text = 'a string'
951 info_text = 'a string'
910
952
911 def validate(self, obj, value):
953 def validate(self, obj, value):
912 if isinstance(value, str):
954 if isinstance(value, str):
913 return value
955 return value
914 self.error(obj, value)
956 self.error(obj, value)
915
957
916
958
917 class CStr(Str):
959 class CStr(Str):
918 """A casting version of the string trait."""
960 """A casting version of the string trait."""
919
961
920 def validate(self, obj, value):
962 def validate(self, obj, value):
921 try:
963 try:
922 return str(value)
964 return str(value)
923 except:
965 except:
924 try:
966 try:
925 return unicode(value)
967 return unicode(value)
926 except:
968 except:
927 self.error(obj, value)
969 self.error(obj, value)
928
970
929
971
930 class Unicode(TraitType):
972 class Unicode(TraitType):
931 """A trait for unicode strings."""
973 """A trait for unicode strings."""
932
974
933 default_value = u''
975 default_value = u''
934 info_text = 'a unicode string'
976 info_text = 'a unicode string'
935
977
936 def validate(self, obj, value):
978 def validate(self, obj, value):
937 if isinstance(value, unicode):
979 if isinstance(value, unicode):
938 return value
980 return value
939 if isinstance(value, str):
981 if isinstance(value, str):
940 return unicode(value)
982 return unicode(value)
941 self.error(obj, value)
983 self.error(obj, value)
942
984
943
985
944 class CUnicode(Unicode):
986 class CUnicode(Unicode):
945 """A casting version of the unicode trait."""
987 """A casting version of the unicode trait."""
946
988
947 def validate(self, obj, value):
989 def validate(self, obj, value):
948 try:
990 try:
949 return unicode(value)
991 return unicode(value)
950 except:
992 except:
951 self.error(obj, value)
993 self.error(obj, value)
952
994
953
995
954 class Bool(TraitType):
996 class Bool(TraitType):
955 """A boolean (True, False) trait."""
997 """A boolean (True, False) trait."""
956
998
957 default_value = False
999 default_value = False
958 info_text = 'a boolean'
1000 info_text = 'a boolean'
959
1001
960 def validate(self, obj, value):
1002 def validate(self, obj, value):
961 if isinstance(value, bool):
1003 if isinstance(value, bool):
962 return value
1004 return value
963 self.error(obj, value)
1005 self.error(obj, value)
964
1006
965
1007
966 class CBool(Bool):
1008 class CBool(Bool):
967 """A casting version of the boolean trait."""
1009 """A casting version of the boolean trait."""
968
1010
969 def validate(self, obj, value):
1011 def validate(self, obj, value):
970 try:
1012 try:
971 return bool(value)
1013 return bool(value)
972 except:
1014 except:
973 self.error(obj, value)
1015 self.error(obj, value)
974
1016
975
1017
976 class Enum(TraitType):
1018 class Enum(TraitType):
977 """An enum that whose value must be in a given sequence."""
1019 """An enum that whose value must be in a given sequence."""
978
1020
979 def __init__(self, values, default_value=None, allow_none=True, **metadata):
1021 def __init__(self, values, default_value=None, allow_none=True, **metadata):
980 self.values = values
1022 self.values = values
981 self._allow_none = allow_none
1023 self._allow_none = allow_none
982 super(Enum, self).__init__(default_value, **metadata)
1024 super(Enum, self).__init__(default_value, **metadata)
983
1025
984 def validate(self, obj, value):
1026 def validate(self, obj, value):
985 if value is None:
1027 if value is None:
986 if self._allow_none:
1028 if self._allow_none:
987 return value
1029 return value
988
1030
989 if value in self.values:
1031 if value in self.values:
990 return value
1032 return value
991 self.error(obj, value)
1033 self.error(obj, value)
992
1034
993 def info(self):
1035 def info(self):
994 """ Returns a description of the trait."""
1036 """ Returns a description of the trait."""
995 result = 'any of ' + repr(self.values)
1037 result = 'any of ' + repr(self.values)
996 if self._allow_none:
1038 if self._allow_none:
997 return result + ' or None'
1039 return result + ' or None'
998 return result
1040 return result
999
1041
1000 class CaselessStrEnum(Enum):
1042 class CaselessStrEnum(Enum):
1001 """An enum of strings that are caseless in validate."""
1043 """An enum of strings that are caseless in validate."""
1002
1044
1003 def validate(self, obj, value):
1045 def validate(self, obj, value):
1004 if value is None:
1046 if value is None:
1005 if self._allow_none:
1047 if self._allow_none:
1006 return value
1048 return value
1007
1049
1008 if not isinstance(value, str):
1050 if not isinstance(value, str):
1009 self.error(obj, value)
1051 self.error(obj, value)
1010
1052
1011 for v in self.values:
1053 for v in self.values:
1012 if v.lower() == value.lower():
1054 if v.lower() == value.lower():
1013 return v
1055 return v
1014 self.error(obj, value)
1056 self.error(obj, value)
1015
1057
1016
1058
1017 class List(Instance):
1059 class List(Instance):
1018 """An instance of a Python list."""
1060 """An instance of a Python list."""
1019
1061
1020 def __init__(self, default_value=None, allow_none=True, **metadata):
1062 def __init__(self, default_value=None, allow_none=True, **metadata):
1021 """Create a list trait type from a list, set, or tuple.
1063 """Create a list trait type from a list, set, or tuple.
1022
1064
1023 The default value is created by doing ``list(default_value)``,
1065 The default value is created by doing ``list(default_value)``,
1024 which creates a copy of the ``default_value``.
1066 which creates a copy of the ``default_value``.
1025 """
1067 """
1026 if default_value is None:
1068 if default_value is None:
1027 args = ((),)
1069 args = ((),)
1028 elif isinstance(default_value, SequenceTypes):
1070 elif isinstance(default_value, SequenceTypes):
1029 args = (default_value,)
1071 args = (default_value,)
1030 else:
1072 else:
1031 raise TypeError('default value of List was %s' % default_value)
1073 raise TypeError('default value of List was %s' % default_value)
1032
1074
1033 super(List,self).__init__(klass=list, args=args,
1075 super(List,self).__init__(klass=list, args=args,
1034 allow_none=allow_none, **metadata)
1076 allow_none=allow_none, **metadata)
1035
1077
1036
1078
1037 class Set(Instance):
1079 class Set(Instance):
1038 """An instance of a Python set."""
1080 """An instance of a Python set."""
1039
1081
1040 def __init__(self, default_value=None, allow_none=True, **metadata):
1082 def __init__(self, default_value=None, allow_none=True, **metadata):
1041 """Create a set trait type from a set, list, or tuple.
1083 """Create a set trait type from a set, list, or tuple.
1042
1084
1043 The default value is created by doing ``set(default_value)``,
1085 The default value is created by doing ``set(default_value)``,
1044 which creates a copy of the ``default_value``.
1086 which creates a copy of the ``default_value``.
1045 """
1087 """
1046 if default_value is None:
1088 if default_value is None:
1047 args = ((),)
1089 args = ((),)
1048 elif isinstance(default_value, SequenceTypes):
1090 elif isinstance(default_value, SequenceTypes):
1049 args = (default_value,)
1091 args = (default_value,)
1050 else:
1092 else:
1051 raise TypeError('default value of Set was %s' % default_value)
1093 raise TypeError('default value of Set was %s' % default_value)
1052
1094
1053 super(Set,self).__init__(klass=set, args=args,
1095 super(Set,self).__init__(klass=set, args=args,
1054 allow_none=allow_none, **metadata)
1096 allow_none=allow_none, **metadata)
1055
1097
1056
1098
1057 class Dict(Instance):
1099 class Dict(Instance):
1058 """An instance of a Python dict."""
1100 """An instance of a Python dict."""
1059
1101
1060 def __init__(self, default_value=None, allow_none=True, **metadata):
1102 def __init__(self, default_value=None, allow_none=True, **metadata):
1061 """Create a dict trait type from a dict.
1103 """Create a dict trait type from a dict.
1062
1104
1063 The default value is created by doing ``dict(default_value)``,
1105 The default value is created by doing ``dict(default_value)``,
1064 which creates a copy of the ``default_value``.
1106 which creates a copy of the ``default_value``.
1065 """
1107 """
1066 if default_value is None:
1108 if default_value is None:
1067 args = ((),)
1109 args = ((),)
1068 elif isinstance(default_value, dict):
1110 elif isinstance(default_value, dict):
1069 args = (default_value,)
1111 args = (default_value,)
1070 elif isinstance(default_value, SequenceTypes):
1112 elif isinstance(default_value, SequenceTypes):
1071 args = (default_value,)
1113 args = (default_value,)
1072 else:
1114 else:
1073 raise TypeError('default value of Dict was %s' % default_value)
1115 raise TypeError('default value of Dict was %s' % default_value)
1074
1116
1075 super(Dict,self).__init__(klass=dict, args=args,
1117 super(Dict,self).__init__(klass=dict, args=args,
1076 allow_none=allow_none, **metadata)
1118 allow_none=allow_none, **metadata)
1077
1119
1078
1120
1079 class TCPAddress(TraitType):
1121 class TCPAddress(TraitType):
1080 """A trait for an (ip, port) tuple.
1122 """A trait for an (ip, port) tuple.
1081
1123
1082 This allows for both IPv4 IP addresses as well as hostnames.
1124 This allows for both IPv4 IP addresses as well as hostnames.
1083 """
1125 """
1084
1126
1085 default_value = ('127.0.0.1', 0)
1127 default_value = ('127.0.0.1', 0)
1086 info_text = 'an (ip, port) tuple'
1128 info_text = 'an (ip, port) tuple'
1087
1129
1088 def validate(self, obj, value):
1130 def validate(self, obj, value):
1089 if isinstance(value, tuple):
1131 if isinstance(value, tuple):
1090 if len(value) == 2:
1132 if len(value) == 2:
1091 if isinstance(value[0], basestring) and isinstance(value[1], int):
1133 if isinstance(value[0], basestring) and isinstance(value[1], int):
1092 port = value[1]
1134 port = value[1]
1093 if port >= 0 and port <= 65535:
1135 if port >= 0 and port <= 65535:
1094 return value
1136 return value
1095 self.error(obj, value)
1137 self.error(obj, value)
General Comments 0
You need to be logged in to leave comments. Login now