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