From 65eb091985acfe858502a7af17c061037ff37ed2 2015-04-09 02:08:14 From: Matthias Bussonnier Date: 2015-04-09 02:08:14 Subject: [PATCH] Merge pull request #8288 from minrk/rm-traitlets Big Split: remove traitlets --- diff --git a/.travis.yml b/.travis.yml index d3ab063..1368359 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,7 +21,7 @@ before_install: - git clone --quiet --depth 1 https://github.com/minrk/travis-wheels travis-wheels - 'if [[ $GROUP != js* ]]; then COVERAGE="--coverage xml"; fi' install: - - pip install -f travis-wheels/wheelhouse -e file://$PWD#egg=ipython[all] coveralls + - pip install -f travis-wheels/wheelhouse -r requirements.txt -e file://$PWD#egg=ipython[all] coveralls before_script: - 'if [[ $GROUP == js* ]]; then python -m IPython.external.mathjax mathjax.zip; fi' script: diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f6f0fdf --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +-e git+https://github.com/ipython/ipython_genutils.git#egg=ipython_genutils +-e git+https://github.com/ipython/traitlets.git#egg=traitlets diff --git a/setup.py b/setup.py index a7679e6..fcec5b1 100755 --- a/setup.py +++ b/setup.py @@ -289,6 +289,7 @@ install_requires = [ 'decorator', 'pickleshare', 'simplegeneric>0.8', + 'traitlets', ] # add platform-specific dependencies diff --git a/traitlets/__init__.py b/traitlets/__init__.py deleted file mode 100644 index ad54a5b..0000000 --- a/traitlets/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# FIXME: import IPython first, to avoid circular imports -# this shouldn't be needed after finishing the big split -import IPython - -from .traitlets import * diff --git a/traitlets/config/__init__.py b/traitlets/config/__init__.py deleted file mode 100644 index 0ae7d63..0000000 --- a/traitlets/config/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# encoding: utf-8 - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from .application import * -from .configurable import * -from .loader import Config diff --git a/traitlets/config/application.py b/traitlets/config/application.py deleted file mode 100644 index d44899e..0000000 --- a/traitlets/config/application.py +++ /dev/null @@ -1,622 +0,0 @@ -# encoding: utf-8 -"""A base class for a configurable application.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from __future__ import print_function - -import json -import logging -import os -import re -import sys -from copy import deepcopy -from collections import defaultdict - -from decorator import decorator - -from traitlets.config.configurable import SingletonConfigurable -from traitlets.config.loader import ( - KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader -) - -from traitlets.traitlets import ( - Unicode, List, Enum, Dict, Instance, TraitError -) -from IPython.utils.importstring import import_item -from IPython.utils.text import indent, wrap_paragraphs, dedent -from IPython.utils import py3compat -from IPython.utils.py3compat import string_types, iteritems - -#----------------------------------------------------------------------------- -# Descriptions for the various sections -#----------------------------------------------------------------------------- - -# merge flags&aliases into options -option_description = """ -Arguments that take values are actually convenience aliases to full -Configurables, whose aliases are listed on the help line. For more information -on full configurables, see '--help-all'. -""".strip() # trim newlines of front and back - -keyvalue_description = """ -Parameters are set from command-line arguments of the form: -`--Class.trait=value`. -This line is evaluated in Python, so simple expressions are allowed, e.g.:: -`--C.a='range(3)'` For setting C.a=[0,1,2]. -""".strip() # trim newlines of front and back - -# sys.argv can be missing, for example when python is embedded. See the docs -# for details: http://docs.python.org/2/c-api/intro.html#embedding-python -if not hasattr(sys, "argv"): - sys.argv = [""] - -subcommand_description = """ -Subcommands are launched as `{app} cmd [args]`. For information on using -subcommand 'cmd', do: `{app} cmd -h`. -""" -# get running program name - -#----------------------------------------------------------------------------- -# Application class -#----------------------------------------------------------------------------- - -@decorator -def catch_config_error(method, app, *args, **kwargs): - """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. - - On a TraitError (generally caused by bad config), this will print the trait's - message, and exit the app. - - For use on init methods, to prevent invoking excepthook on invalid input. - """ - try: - return method(app, *args, **kwargs) - except (TraitError, ArgumentError) as e: - app.print_help() - app.log.fatal("Bad config encountered during initialization:") - app.log.fatal(str(e)) - app.log.debug("Config at the time: %s", app.config) - app.exit(1) - - -class ApplicationError(Exception): - pass - -class LevelFormatter(logging.Formatter): - """Formatter with additional `highlevel` record - - This field is empty if log level is less than highlevel_limit, - otherwise it is formatted with self.highlevel_format. - - Useful for adding 'WARNING' to warning messages, - without adding 'INFO' to info, etc. - """ - highlevel_limit = logging.WARN - highlevel_format = " %(levelname)s |" - - def format(self, record): - if record.levelno >= self.highlevel_limit: - record.highlevel = self.highlevel_format % record.__dict__ - else: - record.highlevel = "" - return super(LevelFormatter, self).format(record) - - -class Application(SingletonConfigurable): - """A singleton application with full configuration support.""" - - # The name of the application, will usually match the name of the command - # line application - name = Unicode(u'application') - - # The description of the application that is printed at the beginning - # of the help. - description = Unicode(u'This is an application.') - # default section descriptions - option_description = Unicode(option_description) - keyvalue_description = Unicode(keyvalue_description) - subcommand_description = Unicode(subcommand_description) - - python_config_loader_class = PyFileConfigLoader - json_config_loader_class = JSONFileConfigLoader - - # The usage and example string that goes at the end of the help string. - examples = Unicode() - - # A sequence of Configurable subclasses whose config=True attributes will - # be exposed at the command line. - classes = [] - @property - def _help_classes(self): - """Define `App.help_classes` if CLI classes should differ from config file classes""" - return getattr(self, 'help_classes', self.classes) - - @property - def _config_classes(self): - """Define `App.config_classes` if config file classes should differ from CLI classes.""" - return getattr(self, 'config_classes', self.classes) - - # The version string of this application. - version = Unicode(u'0.0') - - # the argv used to initialize the application - argv = List() - - # The log level for the application - log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'), - default_value=logging.WARN, - config=True, - help="Set the log level by value or name.") - def _log_level_changed(self, name, old, new): - """Adjust the log level when log_level is set.""" - if isinstance(new, string_types): - new = getattr(logging, new) - self.log_level = new - self.log.setLevel(new) - - _log_formatter_cls = LevelFormatter - - log_datefmt = Unicode("%Y-%m-%d %H:%M:%S", config=True, - help="The date format used by logging formatters for %(asctime)s" - ) - def _log_datefmt_changed(self, name, old, new): - self._log_format_changed('log_format', self.log_format, self.log_format) - - log_format = Unicode("[%(name)s]%(highlevel)s %(message)s", config=True, - help="The Logging format template", - ) - def _log_format_changed(self, name, old, new): - """Change the log formatter when log_format is set.""" - _log_handler = self.log.handlers[0] - _log_formatter = self._log_formatter_cls(fmt=new, datefmt=self.log_datefmt) - _log_handler.setFormatter(_log_formatter) - - - log = Instance(logging.Logger) - def _log_default(self): - """Start logging for this application. - - The default is to log to stderr using a StreamHandler, if no default - handler already exists. The log level starts at logging.WARN, but this - can be adjusted by setting the ``log_level`` attribute. - """ - log = logging.getLogger(self.__class__.__name__) - log.setLevel(self.log_level) - log.propagate = False - _log = log # copied from Logger.hasHandlers() (new in Python 3.2) - while _log: - if _log.handlers: - return log - if not _log.propagate: - break - else: - _log = _log.parent - if sys.executable.endswith('pythonw.exe'): - # this should really go to a file, but file-logging is only - # hooked up in parallel applications - _log_handler = logging.StreamHandler(open(os.devnull, 'w')) - else: - _log_handler = logging.StreamHandler() - _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) - _log_handler.setFormatter(_log_formatter) - log.addHandler(_log_handler) - return log - - # the alias map for configurables - aliases = Dict({'log-level' : 'Application.log_level'}) - - # flags for loading Configurables or store_const style flags - # flags are loaded from this dict by '--key' flags - # this must be a dict of two-tuples, the first element being the Config/dict - # and the second being the help string for the flag - flags = Dict() - def _flags_changed(self, name, old, new): - """ensure flags dict is valid""" - for key,value in iteritems(new): - assert len(value) == 2, "Bad flag: %r:%s"%(key,value) - assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value) - assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value) - - - # subcommands for launching other applications - # if this is not empty, this will be a parent Application - # this must be a dict of two-tuples, - # the first element being the application class/import string - # and the second being the help string for the subcommand - subcommands = Dict() - # parse_command_line will initialize a subapp, if requested - subapp = Instance('traitlets.config.application.Application', allow_none=True) - - # extra command-line arguments that don't set config values - extra_args = List(Unicode) - - - def __init__(self, **kwargs): - SingletonConfigurable.__init__(self, **kwargs) - # Ensure my class is in self.classes, so my attributes appear in command line - # options and config files. - if self.__class__ not in self.classes: - self.classes.insert(0, self.__class__) - - def _config_changed(self, name, old, new): - SingletonConfigurable._config_changed(self, name, old, new) - self.log.debug('Config changed:') - self.log.debug(repr(new)) - - @catch_config_error - def initialize(self, argv=None): - """Do the basic steps to configure me. - - Override in subclasses. - """ - self.parse_command_line(argv) - - - def start(self): - """Start the app mainloop. - - Override in subclasses. - """ - if self.subapp is not None: - return self.subapp.start() - - def print_alias_help(self): - """Print the alias part of the help.""" - if not self.aliases: - return - - lines = [] - classdict = {} - for cls in self._help_classes: - # include all parents (up to, but excluding Configurable) in available names - for c in cls.mro()[:-3]: - classdict[c.__name__] = c - - for alias, longname in iteritems(self.aliases): - classname, traitname = longname.split('.',1) - cls = classdict[classname] - - trait = cls.class_traits(config=True)[traitname] - help = cls.class_get_trait_help(trait).splitlines() - # reformat first line - help[0] = help[0].replace(longname, alias) + ' (%s)'%longname - if len(alias) == 1: - help[0] = help[0].replace('--%s='%alias, '-%s '%alias) - lines.extend(help) - # lines.append('') - print(os.linesep.join(lines)) - - def print_flag_help(self): - """Print the flag part of the help.""" - if not self.flags: - return - - lines = [] - for m, (cfg,help) in iteritems(self.flags): - prefix = '--' if len(m) > 1 else '-' - lines.append(prefix+m) - lines.append(indent(dedent(help.strip()))) - # lines.append('') - print(os.linesep.join(lines)) - - def print_options(self): - if not self.flags and not self.aliases: - return - lines = ['Options'] - lines.append('-'*len(lines[0])) - lines.append('') - for p in wrap_paragraphs(self.option_description): - lines.append(p) - lines.append('') - print(os.linesep.join(lines)) - self.print_flag_help() - self.print_alias_help() - print() - - def print_subcommands(self): - """Print the subcommand part of the help.""" - if not self.subcommands: - return - - lines = ["Subcommands"] - lines.append('-'*len(lines[0])) - lines.append('') - for p in wrap_paragraphs(self.subcommand_description.format( - app=self.name)): - lines.append(p) - lines.append('') - for subc, (cls, help) in iteritems(self.subcommands): - lines.append(subc) - if help: - lines.append(indent(dedent(help.strip()))) - lines.append('') - print(os.linesep.join(lines)) - - def print_help(self, classes=False): - """Print the help for each Configurable class in self.classes. - - If classes=False (the default), only flags and aliases are printed. - """ - self.print_description() - self.print_subcommands() - self.print_options() - - if classes: - help_classes = self._help_classes - if help_classes: - print("Class parameters") - print("----------------") - print() - for p in wrap_paragraphs(self.keyvalue_description): - print(p) - print() - - for cls in help_classes: - cls.class_print_help() - print() - else: - print("To see all available configurables, use `--help-all`") - print() - - self.print_examples() - - - def print_description(self): - """Print the application description.""" - for p in wrap_paragraphs(self.description): - print(p) - print() - - def print_examples(self): - """Print usage and examples. - - This usage string goes at the end of the command line help string - and should contain examples of the application's usage. - """ - if self.examples: - print("Examples") - print("--------") - print() - print(indent(dedent(self.examples.strip()))) - print() - - def print_version(self): - """Print the version string.""" - print(self.version) - - def update_config(self, config): - """Fire the traits events when the config is updated.""" - # Save a copy of the current config. - newconfig = deepcopy(self.config) - # Merge the new config into the current one. - newconfig.merge(config) - # Save the combined config as self.config, which triggers the traits - # events. - self.config = newconfig - - @catch_config_error - def initialize_subcommand(self, subc, argv=None): - """Initialize a subcommand with argv.""" - subapp,help = self.subcommands.get(subc) - - if isinstance(subapp, string_types): - subapp = import_item(subapp) - - # clear existing instances - self.__class__.clear_instance() - # instantiate - self.subapp = subapp.instance(config=self.config) - # and initialize subapp - self.subapp.initialize(argv) - - def flatten_flags(self): - """flatten flags and aliases, so cl-args override as expected. - - This prevents issues such as an alias pointing to InteractiveShell, - but a config file setting the same trait in TerminalInteraciveShell - getting inappropriate priority over the command-line arg. - - Only aliases with exactly one descendent in the class list - will be promoted. - - """ - # build a tree of classes in our list that inherit from a particular - # it will be a dict by parent classname of classes in our list - # that are descendents - mro_tree = defaultdict(list) - for cls in self._help_classes: - clsname = cls.__name__ - for parent in cls.mro()[1:-3]: - # exclude cls itself and Configurable,HasTraits,object - mro_tree[parent.__name__].append(clsname) - # flatten aliases, which have the form: - # { 'alias' : 'Class.trait' } - aliases = {} - for alias, cls_trait in iteritems(self.aliases): - cls,trait = cls_trait.split('.',1) - children = mro_tree[cls] - if len(children) == 1: - # exactly one descendent, promote alias - cls = children[0] - aliases[alias] = '.'.join([cls,trait]) - - # flatten flags, which are of the form: - # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} - flags = {} - for key, (flagdict, help) in iteritems(self.flags): - newflag = {} - for cls, subdict in iteritems(flagdict): - children = mro_tree[cls] - # exactly one descendent, promote flag section - if len(children) == 1: - cls = children[0] - newflag[cls] = subdict - flags[key] = (newflag, help) - return flags, aliases - - @catch_config_error - def parse_command_line(self, argv=None): - """Parse the command line arguments.""" - argv = sys.argv[1:] if argv is None else argv - self.argv = [ py3compat.cast_unicode(arg) for arg in argv ] - - if argv and argv[0] == 'help': - # turn `ipython help notebook` into `ipython notebook -h` - argv = argv[1:] + ['-h'] - - if self.subcommands and len(argv) > 0: - # we have subcommands, and one may have been specified - subc, subargv = argv[0], argv[1:] - if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: - # it's a subcommand, and *not* a flag or class parameter - return self.initialize_subcommand(subc, subargv) - - # Arguments after a '--' argument are for the script IPython may be - # about to run, not IPython iteslf. For arguments parsed here (help and - # version), we want to only search the arguments up to the first - # occurrence of '--', which we're calling interpreted_argv. - try: - interpreted_argv = argv[:argv.index('--')] - except ValueError: - interpreted_argv = argv - - if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')): - self.print_help('--help-all' in interpreted_argv) - self.exit(0) - - if '--version' in interpreted_argv or '-V' in interpreted_argv: - self.print_version() - self.exit(0) - - # flatten flags&aliases, so cl-args get appropriate priority: - flags,aliases = self.flatten_flags() - loader = KVArgParseConfigLoader(argv=argv, aliases=aliases, - flags=flags, log=self.log) - config = loader.load_config() - self.update_config(config) - # store unparsed args in extra_args - self.extra_args = loader.extra_args - - @classmethod - def _load_config_files(cls, basefilename, path=None, log=None): - """Load config files (py,json) by filename and path. - - yield each config object in turn. - """ - - if not isinstance(path, list): - path = [path] - for path in path[::-1]: - # path list is in descending priority order, so load files backwards: - pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log) - jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log) - config = None - for loader in [pyloader, jsonloader]: - try: - config = loader.load_config() - except ConfigFileNotFound: - pass - except Exception: - # try to get the full filename, but it will be empty in the - # unlikely event that the error raised before filefind finished - filename = loader.full_filename or basefilename - # problem while running the file - if log: - log.error("Exception while loading config file %s", - filename, exc_info=True) - else: - if log: - log.debug("Loaded config file: %s", loader.full_filename) - if config: - yield config - - raise StopIteration - - - @catch_config_error - def load_config_file(self, filename, path=None): - """Load config files by filename and path.""" - filename, ext = os.path.splitext(filename) - loaded = [] - for config in self._load_config_files(filename, path=path, log=self.log): - loaded.append(config) - self.update_config(config) - if len(loaded) > 1: - collisions = loaded[0].collisions(loaded[1]) - if collisions: - self.log.warn("Collisions detected in {0}.py and {0}.json config files." - " {0}.json has higher priority: {1}".format( - filename, json.dumps(collisions, indent=2), - )) - - - def generate_config_file(self): - """generate default config file from Configurables""" - lines = ["# Configuration file for %s." % self.name] - lines.append('') - for cls in self._config_classes: - lines.append(cls.class_config_section()) - return '\n'.join(lines) - - def exit(self, exit_status=0): - self.log.debug("Exiting application: %s" % self.name) - sys.exit(exit_status) - - @classmethod - def launch_instance(cls, argv=None, **kwargs): - """Launch a global instance of this Application - - If a global instance already exists, this reinitializes and starts it - """ - app = cls.instance(**kwargs) - app.initialize(argv) - app.start() - -#----------------------------------------------------------------------------- -# utility functions, for convenience -#----------------------------------------------------------------------------- - -def boolean_flag(name, configurable, set_help='', unset_help=''): - """Helper for building basic --trait, --no-trait flags. - - Parameters - ---------- - - name : str - The name of the flag. - configurable : str - The 'Class.trait' string of the trait to be set/unset with the flag - set_help : unicode - help string for --name flag - unset_help : unicode - help string for --no-name flag - - Returns - ------- - - cfg : dict - A dict with two keys: 'name', and 'no-name', for setting and unsetting - the trait, respectively. - """ - # default helpstrings - set_help = set_help or "set %s=True"%configurable - unset_help = unset_help or "set %s=False"%configurable - - cls,trait = configurable.split('.') - - setter = {cls : {trait : True}} - unsetter = {cls : {trait : False}} - return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)} - - -def get_config(): - """Get the config object for the global Application instance, if there is one - - otherwise return an empty config object - """ - if Application.initialized(): - return Application.instance().config - else: - return Config() diff --git a/traitlets/config/configurable.py b/traitlets/config/configurable.py deleted file mode 100644 index 9d79a40..0000000 --- a/traitlets/config/configurable.py +++ /dev/null @@ -1,380 +0,0 @@ -# encoding: utf-8 -"""A base class for objects that are configurable.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from __future__ import print_function - -import logging -from copy import deepcopy - -from .loader import Config, LazyConfigValue -from traitlets.traitlets import HasTraits, Instance -from IPython.utils.text import indent, wrap_paragraphs -from IPython.utils.py3compat import iteritems - - -#----------------------------------------------------------------------------- -# Helper classes for Configurables -#----------------------------------------------------------------------------- - - -class ConfigurableError(Exception): - pass - - -class MultipleInstanceError(ConfigurableError): - pass - -#----------------------------------------------------------------------------- -# Configurable implementation -#----------------------------------------------------------------------------- - -class Configurable(HasTraits): - - config = Instance(Config, (), {}) - parent = Instance('traitlets.config.configurable.Configurable', allow_none=True) - - def __init__(self, **kwargs): - """Create a configurable given a config config. - - Parameters - ---------- - config : Config - If this is empty, default values are used. If config is a - :class:`Config` instance, it will be used to configure the - instance. - parent : Configurable instance, optional - The parent Configurable instance of this object. - - Notes - ----- - Subclasses of Configurable must call the :meth:`__init__` method of - :class:`Configurable` *before* doing anything else and using - :func:`super`:: - - class MyConfigurable(Configurable): - def __init__(self, config=None): - super(MyConfigurable, self).__init__(config=config) - # Then any other code you need to finish initialization. - - This ensures that instances will be configured properly. - """ - parent = kwargs.pop('parent', None) - if parent is not None: - # config is implied from parent - if kwargs.get('config', None) is None: - kwargs['config'] = parent.config - self.parent = parent - - config = kwargs.pop('config', None) - - # load kwarg traits, other than config - super(Configurable, self).__init__(**kwargs) - - # load config - if config is not None: - # We used to deepcopy, but for now we are trying to just save - # by reference. This *could* have side effects as all components - # will share config. In fact, I did find such a side effect in - # _config_changed below. If a config attribute value was a mutable type - # all instances of a component were getting the same copy, effectively - # making that a class attribute. - # self.config = deepcopy(config) - self.config = config - else: - # allow _config_default to return something - self._load_config(self.config) - - # Ensure explicit kwargs are applied after loading config. - # This is usually redundant, but ensures config doesn't override - # explicitly assigned values. - for key, value in kwargs.items(): - setattr(self, key, value) - - #------------------------------------------------------------------------- - # Static trait notifiations - #------------------------------------------------------------------------- - - @classmethod - def section_names(cls): - """return section names as a list""" - return [c.__name__ for c in reversed(cls.__mro__) if - issubclass(c, Configurable) and issubclass(cls, c) - ] - - def _find_my_config(self, cfg): - """extract my config from a global Config object - - will construct a Config object of only the config values that apply to me - based on my mro(), as well as those of my parent(s) if they exist. - - If I am Bar and my parent is Foo, and their parent is Tim, - this will return merge following config sections, in this order:: - - [Bar, Foo.bar, Tim.Foo.Bar] - - With the last item being the highest priority. - """ - cfgs = [cfg] - if self.parent: - cfgs.append(self.parent._find_my_config(cfg)) - my_config = Config() - for c in cfgs: - for sname in self.section_names(): - # Don't do a blind getattr as that would cause the config to - # dynamically create the section with name Class.__name__. - if c._has_section(sname): - my_config.merge(c[sname]) - return my_config - - def _load_config(self, cfg, section_names=None, traits=None): - """load traits from a Config object""" - - if traits is None: - traits = self.traits(config=True) - if section_names is None: - section_names = self.section_names() - - my_config = self._find_my_config(cfg) - - # hold trait notifications until after all config has been loaded - with self.hold_trait_notifications(): - for name, config_value in iteritems(my_config): - if name in traits: - if isinstance(config_value, LazyConfigValue): - # ConfigValue is a wrapper for using append / update on containers - # without having to copy the initial value - initial = getattr(self, name) - config_value = config_value.get_value(initial) - # We have to do a deepcopy here if we don't deepcopy the entire - # config object. If we don't, a mutable config_value will be - # shared by all instances, effectively making it a class attribute. - setattr(self, name, deepcopy(config_value)) - - def _config_changed(self, name, old, new): - """Update all the class traits having ``config=True`` as metadata. - - For any class trait with a ``config`` metadata attribute that is - ``True``, we update the trait with the value of the corresponding - config entry. - """ - # Get all traits with a config metadata entry that is True - traits = self.traits(config=True) - - # We auto-load config section for this class as well as any parent - # classes that are Configurable subclasses. This starts with Configurable - # and works down the mro loading the config for each section. - section_names = self.section_names() - self._load_config(new, traits=traits, section_names=section_names) - - def update_config(self, config): - """Fire the traits events when the config is updated.""" - # Save a copy of the current config. - newconfig = deepcopy(self.config) - # Merge the new config into the current one. - newconfig.merge(config) - # Save the combined config as self.config, which triggers the traits - # events. - self.config = newconfig - - @classmethod - def class_get_help(cls, inst=None): - """Get the help string for this class in ReST format. - - If `inst` is given, it's current trait values will be used in place of - class defaults. - """ - assert inst is None or isinstance(inst, cls) - final_help = [] - final_help.append(u'%s options' % cls.__name__) - final_help.append(len(final_help[0])*u'-') - for k, v in sorted(cls.class_traits(config=True).items()): - help = cls.class_get_trait_help(v, inst) - final_help.append(help) - return '\n'.join(final_help) - - @classmethod - def class_get_trait_help(cls, trait, inst=None): - """Get the help string for a single trait. - - If `inst` is given, it's current trait values will be used in place of - the class default. - """ - assert inst is None or isinstance(inst, cls) - lines = [] - header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__) - lines.append(header) - if inst is not None: - lines.append(indent('Current: %r' % getattr(inst, trait.name), 4)) - else: - try: - dvr = repr(trait.get_default_value()) - except Exception: - dvr = None # ignore defaults we can't construct - if dvr is not None: - if len(dvr) > 64: - dvr = dvr[:61]+'...' - lines.append(indent('Default: %s' % dvr, 4)) - if 'Enum' in trait.__class__.__name__: - # include Enum choices - lines.append(indent('Choices: %r' % (trait.values,))) - - help = trait.get_metadata('help') - if help is not None: - help = '\n'.join(wrap_paragraphs(help, 76)) - lines.append(indent(help, 4)) - return '\n'.join(lines) - - @classmethod - def class_print_help(cls, inst=None): - """Get the help string for a single trait and print it.""" - print(cls.class_get_help(inst)) - - @classmethod - def class_config_section(cls): - """Get the config class config section""" - def c(s): - """return a commented, wrapped block.""" - s = '\n\n'.join(wrap_paragraphs(s, 78)) - - return '# ' + s.replace('\n', '\n# ') - - # section header - breaker = '#' + '-'*78 - s = "# %s configuration" % cls.__name__ - lines = [breaker, s, breaker, ''] - # get the description trait - desc = cls.class_traits().get('description') - if desc: - desc = desc.default_value - else: - # no description trait, use __doc__ - desc = getattr(cls, '__doc__', '') - if desc: - lines.append(c(desc)) - lines.append('') - - parents = [] - for parent in cls.mro(): - # only include parents that are not base classes - # and are not the class itself - # and have some configurable traits to inherit - if parent is not cls and issubclass(parent, Configurable) and \ - parent.class_traits(config=True): - parents.append(parent) - - if parents: - pstr = ', '.join([ p.__name__ for p in parents ]) - lines.append(c('%s will inherit config from: %s'%(cls.__name__, pstr))) - lines.append('') - - for name, trait in iteritems(cls.class_traits(config=True)): - help = trait.get_metadata('help') or '' - lines.append(c(help)) - lines.append('# c.%s.%s = %r'%(cls.__name__, name, trait.get_default_value())) - lines.append('') - return '\n'.join(lines) - - - -class SingletonConfigurable(Configurable): - """A configurable that only allows one instance. - - This class is for classes that should only have one instance of itself - or *any* subclass. To create and retrieve such a class use the - :meth:`SingletonConfigurable.instance` method. - """ - - _instance = None - - @classmethod - def _walk_mro(cls): - """Walk the cls.mro() for parent classes that are also singletons - - For use in instance() - """ - - for subclass in cls.mro(): - if issubclass(cls, subclass) and \ - issubclass(subclass, SingletonConfigurable) and \ - subclass != SingletonConfigurable: - yield subclass - - @classmethod - def clear_instance(cls): - """unset _instance for this class and singleton parents. - """ - if not cls.initialized(): - return - for subclass in cls._walk_mro(): - if isinstance(subclass._instance, cls): - # only clear instances that are instances - # of the calling class - subclass._instance = None - - @classmethod - def instance(cls, *args, **kwargs): - """Returns a global instance of this class. - - This method create a new instance if none have previously been created - and returns a previously created instance is one already exists. - - The arguments and keyword arguments passed to this method are passed - on to the :meth:`__init__` method of the class upon instantiation. - - Examples - -------- - - Create a singleton class using instance, and retrieve it:: - - >>> from traitlets.config.configurable import SingletonConfigurable - >>> class Foo(SingletonConfigurable): pass - >>> foo = Foo.instance() - >>> foo == Foo.instance() - True - - Create a subclass that is retrived using the base class instance:: - - >>> class Bar(SingletonConfigurable): pass - >>> class Bam(Bar): pass - >>> bam = Bam.instance() - >>> bam == Bar.instance() - True - """ - # Create and save the instance - if cls._instance is None: - inst = cls(*args, **kwargs) - # Now make sure that the instance will also be returned by - # parent classes' _instance attribute. - for subclass in cls._walk_mro(): - subclass._instance = inst - - if isinstance(cls._instance, cls): - return cls._instance - else: - raise MultipleInstanceError( - 'Multiple incompatible subclass instances of ' - '%s are being created.' % cls.__name__ - ) - - @classmethod - def initialized(cls): - """Has an instance been created?""" - return hasattr(cls, "_instance") and cls._instance is not None - - -class LoggingConfigurable(Configurable): - """A parent class for Configurables that log. - - Subclasses have a log trait, and the default behavior - is to get the logger from the currently running Application. - """ - - log = Instance('logging.Logger') - def _log_default(self): - from IPython.utils import log - return log.get_logger() - - diff --git a/traitlets/config/loader.py b/traitlets/config/loader.py deleted file mode 100644 index 09763c0..0000000 --- a/traitlets/config/loader.py +++ /dev/null @@ -1,837 +0,0 @@ -# encoding: utf-8 -"""A simple configuration system.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -import argparse -import copy -import logging -import os -import re -import sys -import json -from ast import literal_eval - -from IPython.utils.path import filefind, get_ipython_dir -from IPython.utils import py3compat -from IPython.utils.encoding import DEFAULT_ENCODING -from IPython.utils.py3compat import unicode_type, iteritems -from traitlets.traitlets import HasTraits, List, Any - -#----------------------------------------------------------------------------- -# Exceptions -#----------------------------------------------------------------------------- - - -class ConfigError(Exception): - pass - -class ConfigLoaderError(ConfigError): - pass - -class ConfigFileNotFound(ConfigError): - pass - -class ArgumentError(ConfigLoaderError): - pass - -#----------------------------------------------------------------------------- -# Argparse fix -#----------------------------------------------------------------------------- - -# Unfortunately argparse by default prints help messages to stderr instead of -# stdout. This makes it annoying to capture long help screens at the command -# line, since one must know how to pipe stderr, which many users don't know how -# to do. So we override the print_help method with one that defaults to -# stdout and use our class instead. - -class ArgumentParser(argparse.ArgumentParser): - """Simple argparse subclass that prints help to stdout by default.""" - - def print_help(self, file=None): - if file is None: - file = sys.stdout - return super(ArgumentParser, self).print_help(file) - - print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ - -#----------------------------------------------------------------------------- -# Config class for holding config information -#----------------------------------------------------------------------------- - -class LazyConfigValue(HasTraits): - """Proxy object for exposing methods on configurable containers - - Exposes: - - - append, extend, insert on lists - - update on dicts - - update, add on sets - """ - - _value = None - - # list methods - _extend = List() - _prepend = List() - - def append(self, obj): - self._extend.append(obj) - - def extend(self, other): - self._extend.extend(other) - - def prepend(self, other): - """like list.extend, but for the front""" - self._prepend[:0] = other - - _inserts = List() - def insert(self, index, other): - if not isinstance(index, int): - raise TypeError("An integer is required") - self._inserts.append((index, other)) - - # dict methods - # update is used for both dict and set - _update = Any() - def update(self, other): - if self._update is None: - if isinstance(other, dict): - self._update = {} - else: - self._update = set() - self._update.update(other) - - # set methods - def add(self, obj): - self.update({obj}) - - def get_value(self, initial): - """construct the value from the initial one - - after applying any insert / extend / update changes - """ - if self._value is not None: - return self._value - value = copy.deepcopy(initial) - if isinstance(value, list): - for idx, obj in self._inserts: - value.insert(idx, obj) - value[:0] = self._prepend - value.extend(self._extend) - - elif isinstance(value, dict): - if self._update: - value.update(self._update) - elif isinstance(value, set): - if self._update: - value.update(self._update) - self._value = value - return value - - def to_dict(self): - """return JSONable dict form of my data - - Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples. - """ - d = {} - if self._update: - d['update'] = self._update - if self._extend: - d['extend'] = self._extend - if self._prepend: - d['prepend'] = self._prepend - elif self._inserts: - d['inserts'] = self._inserts - return d - - -def _is_section_key(key): - """Is a Config key a section name (does it start with a capital)?""" - if key and key[0].upper()==key[0] and not key.startswith('_'): - return True - else: - return False - - -class Config(dict): - """An attribute based dict that can do smart merges.""" - - def __init__(self, *args, **kwds): - dict.__init__(self, *args, **kwds) - self._ensure_subconfig() - - def _ensure_subconfig(self): - """ensure that sub-dicts that should be Config objects are - - casts dicts that are under section keys to Config objects, - which is necessary for constructing Config objects from dict literals. - """ - for key in self: - obj = self[key] - if _is_section_key(key) \ - and isinstance(obj, dict) \ - and not isinstance(obj, Config): - setattr(self, key, Config(obj)) - - def _merge(self, other): - """deprecated alias, use Config.merge()""" - self.merge(other) - - def merge(self, other): - """merge another config object into this one""" - to_update = {} - for k, v in iteritems(other): - if k not in self: - to_update[k] = copy.deepcopy(v) - else: # I have this key - if isinstance(v, Config) and isinstance(self[k], Config): - # Recursively merge common sub Configs - self[k].merge(v) - else: - # Plain updates for non-Configs - to_update[k] = copy.deepcopy(v) - - self.update(to_update) - - def collisions(self, other): - """Check for collisions between two config objects. - - Returns a dict of the form {"Class": {"trait": "collision message"}}`, - indicating which values have been ignored. - - An empty dict indicates no collisions. - """ - collisions = {} - for section in self: - if section not in other: - continue - mine = self[section] - theirs = other[section] - for key in mine: - if key in theirs and mine[key] != theirs[key]: - collisions.setdefault(section, {}) - collisions[section][key] = "%r ignored, using %r" % (mine[key], theirs[key]) - return collisions - - def __contains__(self, key): - # allow nested contains of the form `"Section.key" in config` - if '.' in key: - first, remainder = key.split('.', 1) - if first not in self: - return False - return remainder in self[first] - - return super(Config, self).__contains__(key) - - # .has_key is deprecated for dictionaries. - has_key = __contains__ - - def _has_section(self, key): - return _is_section_key(key) and key in self - - def copy(self): - return type(self)(dict.copy(self)) - # copy nested config objects - for k, v in self.items(): - if isinstance(v, Config): - new_config[k] = v.copy() - return new_config - - def __copy__(self): - return self.copy() - - def __deepcopy__(self, memo): - new_config = type(self)() - for key, value in self.items(): - if isinstance(value, (Config, LazyConfigValue)): - # deep copy config objects - value = copy.deepcopy(value, memo) - elif type(value) in {dict, list, set, tuple}: - # shallow copy plain container traits - value = copy.copy(value) - new_config[key] = value - return new_config - - def __getitem__(self, key): - try: - return dict.__getitem__(self, key) - except KeyError: - if _is_section_key(key): - c = Config() - dict.__setitem__(self, key, c) - return c - elif not key.startswith('_'): - # undefined, create lazy value, used for container methods - v = LazyConfigValue() - dict.__setitem__(self, key, v) - return v - else: - raise KeyError - - def __setitem__(self, key, value): - if _is_section_key(key): - if not isinstance(value, Config): - raise ValueError('values whose keys begin with an uppercase ' - 'char must be Config instances: %r, %r' % (key, value)) - dict.__setitem__(self, key, value) - - def __getattr__(self, key): - if key.startswith('__'): - return dict.__getattr__(self, key) - try: - return self.__getitem__(key) - except KeyError as e: - raise AttributeError(e) - - def __setattr__(self, key, value): - if key.startswith('__'): - return dict.__setattr__(self, key, value) - try: - self.__setitem__(key, value) - except KeyError as e: - raise AttributeError(e) - - def __delattr__(self, key): - if key.startswith('__'): - return dict.__delattr__(self, key) - try: - dict.__delitem__(self, key) - except KeyError as e: - raise AttributeError(e) - - -#----------------------------------------------------------------------------- -# Config loading classes -#----------------------------------------------------------------------------- - - -class ConfigLoader(object): - """A object for loading configurations from just about anywhere. - - The resulting configuration is packaged as a :class:`Config`. - - Notes - ----- - A :class:`ConfigLoader` does one thing: load a config from a source - (file, command line arguments) and returns the data as a :class:`Config` object. - There are lots of things that :class:`ConfigLoader` does not do. It does - not implement complex logic for finding config files. It does not handle - default values or merge multiple configs. These things need to be - handled elsewhere. - """ - - def _log_default(self): - from traitlets.log import get_logger - return get_logger() - - def __init__(self, log=None): - """A base class for config loaders. - - log : instance of :class:`logging.Logger` to use. - By default loger of :meth:`traitlets.config.application.Application.instance()` - will be used - - Examples - -------- - - >>> cl = ConfigLoader() - >>> config = cl.load_config() - >>> config - {} - """ - self.clear() - if log is None: - self.log = self._log_default() - self.log.debug('Using default logger') - else: - self.log = log - - def clear(self): - self.config = Config() - - def load_config(self): - """Load a config from somewhere, return a :class:`Config` instance. - - Usually, this will cause self.config to be set and then returned. - However, in most cases, :meth:`ConfigLoader.clear` should be called - to erase any previous state. - """ - self.clear() - return self.config - - -class FileConfigLoader(ConfigLoader): - """A base class for file based configurations. - - As we add more file based config loaders, the common logic should go - here. - """ - - def __init__(self, filename, path=None, **kw): - """Build a config loader for a filename and path. - - Parameters - ---------- - filename : str - The file name of the config file. - path : str, list, tuple - The path to search for the config file on, or a sequence of - paths to try in order. - """ - super(FileConfigLoader, self).__init__(**kw) - self.filename = filename - self.path = path - self.full_filename = '' - - def _find_file(self): - """Try to find the file by searching the paths.""" - self.full_filename = filefind(self.filename, self.path) - -class JSONFileConfigLoader(FileConfigLoader): - """A JSON file loader for config""" - - def load_config(self): - """Load the config from a file and return it as a Config object.""" - self.clear() - try: - self._find_file() - except IOError as e: - raise ConfigFileNotFound(str(e)) - dct = self._read_file_as_dict() - self.config = self._convert_to_config(dct) - return self.config - - def _read_file_as_dict(self): - with open(self.full_filename) as f: - return json.load(f) - - def _convert_to_config(self, dictionary): - if 'version' in dictionary: - version = dictionary.pop('version') - else: - version = 1 - self.log.warn("Unrecognized JSON config file version, assuming version {}".format(version)) - - if version == 1: - return Config(dictionary) - else: - raise ValueError('Unknown version of JSON config file: {version}'.format(version=version)) - - -class PyFileConfigLoader(FileConfigLoader): - """A config loader for pure python files. - - This is responsible for locating a Python config file by filename and - path, then executing it to construct a Config object. - """ - - def load_config(self): - """Load the config from a file and return it as a Config object.""" - self.clear() - try: - self._find_file() - except IOError as e: - raise ConfigFileNotFound(str(e)) - self._read_file_as_dict() - return self.config - - def load_subconfig(self, fname, path=None): - """Injected into config file namespace as load_subconfig""" - if path is None: - path = self.path - - loader = self.__class__(fname, path) - try: - sub_config = loader.load_config() - except ConfigFileNotFound: - # Pass silently if the sub config is not there, - # treat it as an empty config file. - pass - else: - self.config.merge(sub_config) - - def _read_file_as_dict(self): - """Load the config file into self.config, with recursive loading.""" - def get_config(): - """Unnecessary now, but a deprecation warning is more trouble than it's worth.""" - return self.config - - namespace = dict( - c=self.config, - load_subconfig=self.load_subconfig, - get_config=get_config, - __file__=self.full_filename, - ) - fs_encoding = sys.getfilesystemencoding() or 'ascii' - conf_filename = self.full_filename.encode(fs_encoding) - py3compat.execfile(conf_filename, namespace) - - -class CommandLineConfigLoader(ConfigLoader): - """A config loader for command line arguments. - - As we add more command line based loaders, the common logic should go - here. - """ - - def _exec_config_str(self, lhs, rhs): - """execute self.config. = - - * expands ~ with expanduser - * tries to assign with literal_eval, otherwise assigns with just the string, - allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* - equivalent are `--C.a=4` and `--C.a='4'`. - """ - rhs = os.path.expanduser(rhs) - try: - # Try to see if regular Python syntax will work. This - # won't handle strings as the quote marks are removed - # by the system shell. - value = literal_eval(rhs) - except (NameError, SyntaxError, ValueError): - # This case happens if the rhs is a string. - value = rhs - - exec(u'self.config.%s = value' % lhs) - - def _load_flag(self, cfg): - """update self.config from a flag, which can be a dict or Config""" - if isinstance(cfg, (dict, Config)): - # don't clobber whole config sections, update - # each section from config: - for sec,c in iteritems(cfg): - self.config[sec].update(c) - else: - raise TypeError("Invalid flag: %r" % cfg) - -# raw --identifier=value pattern -# but *also* accept '-' as wordsep, for aliases -# accepts: --foo=a -# --Class.trait=value -# --alias-name=value -# rejects: -foo=value -# --foo -# --Class.trait -kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*') - -# just flags, no assignments, with two *or one* leading '-' -# accepts: --foo -# -foo-bar-again -# rejects: --anything=anything -# --two.word - -flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$') - -class KeyValueConfigLoader(CommandLineConfigLoader): - """A config loader that loads key value pairs from the command line. - - This allows command line options to be gives in the following form:: - - ipython --profile="foo" --InteractiveShell.autocall=False - """ - - def __init__(self, argv=None, aliases=None, flags=None, **kw): - """Create a key value pair config loader. - - Parameters - ---------- - argv : list - A list that has the form of sys.argv[1:] which has unicode - elements of the form u"key=value". If this is None (default), - then sys.argv[1:] will be used. - aliases : dict - A dict of aliases for configurable traits. - Keys are the short aliases, Values are the resolved trait. - Of the form: `{'alias' : 'Configurable.trait'}` - flags : dict - A dict of flags, keyed by str name. Vaues can be Config objects, - dicts, or "key=value" strings. If Config or dict, when the flag - is triggered, The flag is loaded as `self.config.update(m)`. - - Returns - ------- - config : Config - The resulting Config object. - - Examples - -------- - - >>> from traitlets.config.loader import KeyValueConfigLoader - >>> cl = KeyValueConfigLoader() - >>> d = cl.load_config(["--A.name='brian'","--B.number=0"]) - >>> sorted(d.items()) - [('A', {'name': 'brian'}), ('B', {'number': 0})] - """ - super(KeyValueConfigLoader, self).__init__(**kw) - if argv is None: - argv = sys.argv[1:] - self.argv = argv - self.aliases = aliases or {} - self.flags = flags or {} - - - def clear(self): - super(KeyValueConfigLoader, self).clear() - self.extra_args = [] - - - def _decode_argv(self, argv, enc=None): - """decode argv if bytes, using stdin.encoding, falling back on default enc""" - uargv = [] - if enc is None: - enc = DEFAULT_ENCODING - for arg in argv: - if not isinstance(arg, unicode_type): - # only decode if not already decoded - arg = arg.decode(enc) - uargv.append(arg) - return uargv - - - def load_config(self, argv=None, aliases=None, flags=None): - """Parse the configuration and generate the Config object. - - After loading, any arguments that are not key-value or - flags will be stored in self.extra_args - a list of - unparsed command-line arguments. This is used for - arguments such as input files or subcommands. - - Parameters - ---------- - argv : list, optional - A list that has the form of sys.argv[1:] which has unicode - elements of the form u"key=value". If this is None (default), - then self.argv will be used. - aliases : dict - A dict of aliases for configurable traits. - Keys are the short aliases, Values are the resolved trait. - Of the form: `{'alias' : 'Configurable.trait'}` - flags : dict - A dict of flags, keyed by str name. Values can be Config objects - or dicts. When the flag is triggered, The config is loaded as - `self.config.update(cfg)`. - """ - self.clear() - if argv is None: - argv = self.argv - if aliases is None: - aliases = self.aliases - if flags is None: - flags = self.flags - - # ensure argv is a list of unicode strings: - uargv = self._decode_argv(argv) - for idx,raw in enumerate(uargv): - # strip leading '-' - item = raw.lstrip('-') - - if raw == '--': - # don't parse arguments after '--' - # this is useful for relaying arguments to scripts, e.g. - # ipython -i foo.py --matplotlib=qt -- args after '--' go-to-foo.py - self.extra_args.extend(uargv[idx+1:]) - break - - if kv_pattern.match(raw): - lhs,rhs = item.split('=',1) - # Substitute longnames for aliases. - if lhs in aliases: - lhs = aliases[lhs] - if '.' not in lhs: - # probably a mistyped alias, but not technically illegal - self.log.warn("Unrecognized alias: '%s', it will probably have no effect.", raw) - try: - self._exec_config_str(lhs, rhs) - except Exception: - raise ArgumentError("Invalid argument: '%s'" % raw) - - elif flag_pattern.match(raw): - if item in flags: - cfg,help = flags[item] - self._load_flag(cfg) - else: - raise ArgumentError("Unrecognized flag: '%s'"%raw) - elif raw.startswith('-'): - kv = '--'+item - if kv_pattern.match(kv): - raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) - else: - raise ArgumentError("Invalid argument: '%s'"%raw) - else: - # keep all args that aren't valid in a list, - # in case our parent knows what to do with them. - self.extra_args.append(item) - return self.config - -class ArgParseConfigLoader(CommandLineConfigLoader): - """A loader that uses the argparse module to load from the command line.""" - - def __init__(self, argv=None, aliases=None, flags=None, log=None, *parser_args, **parser_kw): - """Create a config loader for use with argparse. - - Parameters - ---------- - - argv : optional, list - If given, used to read command-line arguments from, otherwise - sys.argv[1:] is used. - - parser_args : tuple - A tuple of positional arguments that will be passed to the - constructor of :class:`argparse.ArgumentParser`. - - parser_kw : dict - A tuple of keyword arguments that will be passed to the - constructor of :class:`argparse.ArgumentParser`. - - Returns - ------- - config : Config - The resulting Config object. - """ - super(CommandLineConfigLoader, self).__init__(log=log) - self.clear() - if argv is None: - argv = sys.argv[1:] - self.argv = argv - self.aliases = aliases or {} - self.flags = flags or {} - - self.parser_args = parser_args - self.version = parser_kw.pop("version", None) - kwargs = dict(argument_default=argparse.SUPPRESS) - kwargs.update(parser_kw) - self.parser_kw = kwargs - - def load_config(self, argv=None, aliases=None, flags=None): - """Parse command line arguments and return as a Config object. - - Parameters - ---------- - - args : optional, list - If given, a list with the structure of sys.argv[1:] to parse - arguments from. If not given, the instance's self.argv attribute - (given at construction time) is used.""" - self.clear() - if argv is None: - argv = self.argv - if aliases is None: - aliases = self.aliases - if flags is None: - flags = self.flags - self._create_parser(aliases, flags) - self._parse_args(argv) - self._convert_to_config() - return self.config - - def get_extra_args(self): - if hasattr(self, 'extra_args'): - return self.extra_args - else: - return [] - - def _create_parser(self, aliases=None, flags=None): - self.parser = ArgumentParser(*self.parser_args, **self.parser_kw) - self._add_arguments(aliases, flags) - - def _add_arguments(self, aliases=None, flags=None): - raise NotImplementedError("subclasses must implement _add_arguments") - - def _parse_args(self, args): - """self.parser->self.parsed_data""" - # decode sys.argv to support unicode command-line options - enc = DEFAULT_ENCODING - uargs = [py3compat.cast_unicode(a, enc) for a in args] - self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs) - - def _convert_to_config(self): - """self.parsed_data->self.config""" - for k, v in iteritems(vars(self.parsed_data)): - exec("self.config.%s = v"%k, locals(), globals()) - -class KVArgParseConfigLoader(ArgParseConfigLoader): - """A config loader that loads aliases and flags with argparse, - but will use KVLoader for the rest. This allows better parsing - of common args, such as `ipython -c 'print 5'`, but still gets - arbitrary config with `ipython --InteractiveShell.use_readline=False`""" - - def _add_arguments(self, aliases=None, flags=None): - self.alias_flags = {} - # print aliases, flags - if aliases is None: - aliases = self.aliases - if flags is None: - flags = self.flags - paa = self.parser.add_argument - for key,value in iteritems(aliases): - if key in flags: - # flags - nargs = '?' - else: - nargs = None - if len(key) is 1: - paa('-'+key, '--'+key, type=unicode_type, dest=value, nargs=nargs) - else: - paa('--'+key, type=unicode_type, dest=value, nargs=nargs) - for key, (value, help) in iteritems(flags): - if key in self.aliases: - # - self.alias_flags[self.aliases[key]] = value - continue - if len(key) is 1: - paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value) - else: - paa('--'+key, action='append_const', dest='_flags', const=value) - - def _convert_to_config(self): - """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" - # remove subconfigs list from namespace before transforming the Namespace - if '_flags' in self.parsed_data: - subcs = self.parsed_data._flags - del self.parsed_data._flags - else: - subcs = [] - - for k, v in iteritems(vars(self.parsed_data)): - if v is None: - # it was a flag that shares the name of an alias - subcs.append(self.alias_flags[k]) - else: - # eval the KV assignment - self._exec_config_str(k, v) - - for subc in subcs: - self._load_flag(subc) - - if self.extra_args: - sub_parser = KeyValueConfigLoader(log=self.log) - sub_parser.load_config(self.extra_args) - self.config.merge(sub_parser.config) - self.extra_args = sub_parser.extra_args - - -def load_pyconfig_files(config_files, path): - """Load multiple Python config files, merging each of them in turn. - - Parameters - ========== - config_files : list of str - List of config files names to load and merge into the config. - path : unicode - The full path to the location of the config files. - """ - config = Config() - for cf in config_files: - loader = PyFileConfigLoader(cf, path=path) - try: - next_config = loader.load_config() - except ConfigFileNotFound: - pass - except: - raise - else: - config.merge(next_config) - return config diff --git a/traitlets/config/manager.py b/traitlets/config/manager.py deleted file mode 100644 index b6d47f0..0000000 --- a/traitlets/config/manager.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Manager to read and modify config data in JSON files. -""" -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. -import errno -import io -import json -import os - -from traitlets.config import LoggingConfigurable -from IPython.utils.py3compat import PY3 -from traitlets.traitlets import Unicode - - -def recursive_update(target, new): - """Recursively update one dictionary using another. - - None values will delete their keys. - """ - for k, v in new.items(): - if isinstance(v, dict): - if k not in target: - target[k] = {} - recursive_update(target[k], v) - if not target[k]: - # Prune empty subdicts - del target[k] - - elif v is None: - target.pop(k, None) - - else: - target[k] = v - - -class BaseJSONConfigManager(LoggingConfigurable): - """General JSON config manager - - Deals with persisting/storing config in a json file - """ - - config_dir = Unicode('.') - - def ensure_config_dir_exists(self): - try: - os.mkdir(self.config_dir, 0o755) - except OSError as e: - if e.errno != errno.EEXIST: - raise - - def file_name(self, section_name): - return os.path.join(self.config_dir, section_name+'.json') - - def get(self, section_name): - """Retrieve the config data for the specified section. - - Returns the data as a dictionary, or an empty dictionary if the file - doesn't exist. - """ - filename = self.file_name(section_name) - if os.path.isfile(filename): - with io.open(filename, encoding='utf-8') as f: - return json.load(f) - else: - return {} - - def set(self, section_name, data): - """Store the given config data. - """ - filename = self.file_name(section_name) - self.ensure_config_dir_exists() - - if PY3: - f = io.open(filename, 'w', encoding='utf-8') - else: - f = open(filename, 'wb') - with f: - json.dump(data, f, indent=2) - - def update(self, section_name, new_data): - """Modify the config section by recursively updating it with new_data. - - Returns the modified config data as a dictionary. - """ - data = self.get(section_name) - recursive_update(data, new_data) - self.set(section_name, data) - return data diff --git a/traitlets/config/tests/__init__.py b/traitlets/config/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/traitlets/config/tests/__init__.py +++ /dev/null diff --git a/traitlets/config/tests/test_application.py b/traitlets/config/tests/test_application.py deleted file mode 100644 index 515ba95..0000000 --- a/traitlets/config/tests/test_application.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding: utf-8 -""" -Tests for traitlets.config.application.Application -""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -import logging -import os -from io import StringIO -from unittest import TestCase - -pjoin = os.path.join - -import nose.tools as nt - -from traitlets.config.configurable import Configurable -from traitlets.config.loader import Config - -from traitlets.config.application import ( - Application -) - -from IPython.utils.tempdir import TemporaryDirectory -from traitlets.traitlets import ( - Bool, Unicode, Integer, List, Dict -) - - -class Foo(Configurable): - - i = Integer(0, config=True, help="The integer i.") - j = Integer(1, config=True, help="The integer j.") - name = Unicode(u'Brian', config=True, help="First name.") - - -class Bar(Configurable): - - b = Integer(0, config=True, help="The integer b.") - enabled = Bool(True, config=True, help="Enable bar.") - - -class MyApp(Application): - - name = Unicode(u'myapp') - running = Bool(False, config=True, - help="Is the app running?") - classes = List([Bar, Foo]) - config_file = Unicode(u'', config=True, - help="Load this config file") - - aliases = Dict({ - 'i' : 'Foo.i', - 'j' : 'Foo.j', - 'name' : 'Foo.name', - 'enabled' : 'Bar.enabled', - 'log-level' : 'Application.log_level', - }) - - flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"), - disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False"), - crit=({'Application' : {'log_level' : logging.CRITICAL}}, - "set level=CRITICAL"), - )) - - def init_foo(self): - self.foo = Foo(parent=self) - - def init_bar(self): - self.bar = Bar(parent=self) - - -class TestApplication(TestCase): - - def test_log(self): - stream = StringIO() - app = MyApp(log_level=logging.INFO) - handler = logging.StreamHandler(stream) - # trigger reconstruction of the log formatter - app.log.handlers = [handler] - app.log_format = "%(message)s" - app.log_datefmt = "%Y-%m-%d %H:%M" - app.log.info("hello") - nt.assert_in("hello", stream.getvalue()) - - def test_basic(self): - app = MyApp() - self.assertEqual(app.name, u'myapp') - self.assertEqual(app.running, False) - self.assertEqual(app.classes, [MyApp,Bar,Foo]) - self.assertEqual(app.config_file, u'') - - def test_config(self): - app = MyApp() - app.parse_command_line(["--i=10","--Foo.j=10","--enabled=False","--log-level=50"]) - config = app.config - self.assertEqual(config.Foo.i, 10) - self.assertEqual(config.Foo.j, 10) - self.assertEqual(config.Bar.enabled, False) - self.assertEqual(config.MyApp.log_level,50) - - def test_config_propagation(self): - app = MyApp() - app.parse_command_line(["--i=10","--Foo.j=10","--enabled=False","--log-level=50"]) - app.init_foo() - app.init_bar() - self.assertEqual(app.foo.i, 10) - self.assertEqual(app.foo.j, 10) - self.assertEqual(app.bar.enabled, False) - - def test_flags(self): - app = MyApp() - app.parse_command_line(["--disable"]) - app.init_bar() - self.assertEqual(app.bar.enabled, False) - app.parse_command_line(["--enable"]) - app.init_bar() - self.assertEqual(app.bar.enabled, True) - - def test_aliases(self): - app = MyApp() - app.parse_command_line(["--i=5", "--j=10"]) - app.init_foo() - self.assertEqual(app.foo.i, 5) - app.init_foo() - self.assertEqual(app.foo.j, 10) - - def test_flag_clobber(self): - """test that setting flags doesn't clobber existing settings""" - app = MyApp() - app.parse_command_line(["--Bar.b=5", "--disable"]) - app.init_bar() - self.assertEqual(app.bar.enabled, False) - self.assertEqual(app.bar.b, 5) - app.parse_command_line(["--enable", "--Bar.b=10"]) - app.init_bar() - self.assertEqual(app.bar.enabled, True) - self.assertEqual(app.bar.b, 10) - - def test_flatten_flags(self): - cfg = Config() - cfg.MyApp.log_level = logging.WARN - app = MyApp() - app.update_config(cfg) - self.assertEqual(app.log_level, logging.WARN) - self.assertEqual(app.config.MyApp.log_level, logging.WARN) - app.initialize(["--crit"]) - self.assertEqual(app.log_level, logging.CRITICAL) - # this would be app.config.Application.log_level if it failed: - self.assertEqual(app.config.MyApp.log_level, logging.CRITICAL) - - def test_flatten_aliases(self): - cfg = Config() - cfg.MyApp.log_level = logging.WARN - app = MyApp() - app.update_config(cfg) - self.assertEqual(app.log_level, logging.WARN) - self.assertEqual(app.config.MyApp.log_level, logging.WARN) - app.initialize(["--log-level", "CRITICAL"]) - self.assertEqual(app.log_level, logging.CRITICAL) - # this would be app.config.Application.log_level if it failed: - self.assertEqual(app.config.MyApp.log_level, "CRITICAL") - - def test_extra_args(self): - app = MyApp() - app.parse_command_line(["--Bar.b=5", 'extra', "--disable", 'args']) - app.init_bar() - self.assertEqual(app.bar.enabled, False) - self.assertEqual(app.bar.b, 5) - self.assertEqual(app.extra_args, ['extra', 'args']) - app = MyApp() - app.parse_command_line(["--Bar.b=5", '--', 'extra', "--disable", 'args']) - app.init_bar() - self.assertEqual(app.bar.enabled, True) - self.assertEqual(app.bar.b, 5) - self.assertEqual(app.extra_args, ['extra', '--disable', 'args']) - - def test_unicode_argv(self): - app = MyApp() - app.parse_command_line(['ünîcødé']) - - def test_multi_file(self): - app = MyApp() - app.log = logging.getLogger() - name = 'config.py' - with TemporaryDirectory('_1') as td1: - with open(pjoin(td1, name), 'w') as f1: - f1.write("get_config().MyApp.Bar.b = 1") - with TemporaryDirectory('_2') as td2: - with open(pjoin(td2, name), 'w') as f2: - f2.write("get_config().MyApp.Bar.b = 2") - app.load_config_file(name, path=[td2, td1]) - app.init_bar() - self.assertEqual(app.bar.b, 2) - app.load_config_file(name, path=[td1, td2]) - app.init_bar() - self.assertEqual(app.bar.b, 1) - diff --git a/traitlets/config/tests/test_configurable.py b/traitlets/config/tests/test_configurable.py deleted file mode 100644 index a6f659a..0000000 --- a/traitlets/config/tests/test_configurable.py +++ /dev/null @@ -1,378 +0,0 @@ -# encoding: utf-8 -"""Tests for traitlets.config.configurable""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from unittest import TestCase - -from traitlets.config.configurable import ( - Configurable, - SingletonConfigurable -) - -from traitlets.traitlets import ( - Integer, Float, Unicode, List, Dict, Set, -) - -from traitlets.config.loader import Config -from IPython.utils.py3compat import PY3 - - -class MyConfigurable(Configurable): - a = Integer(1, config=True, help="The integer a.") - b = Float(1.0, config=True, help="The integer b.") - c = Unicode('no config') - - -mc_help=u"""MyConfigurable options ----------------------- ---MyConfigurable.a= - Default: 1 - The integer a. ---MyConfigurable.b= - Default: 1.0 - The integer b.""" - -mc_help_inst=u"""MyConfigurable options ----------------------- ---MyConfigurable.a= - Current: 5 - The integer a. ---MyConfigurable.b= - Current: 4.0 - The integer b.""" - -# On Python 3, the Integer trait is a synonym for Int -if PY3: - mc_help = mc_help.replace(u"", u"") - mc_help_inst = mc_help_inst.replace(u"", u"") - -class Foo(Configurable): - a = Integer(0, config=True, help="The integer a.") - b = Unicode('nope', config=True) - - -class Bar(Foo): - b = Unicode('gotit', config=False, help="The string b.") - c = Float(config=True, help="The string c.") - - -class TestConfigurable(TestCase): - - def test_default(self): - c1 = Configurable() - c2 = Configurable(config=c1.config) - c3 = Configurable(config=c2.config) - self.assertEqual(c1.config, c2.config) - self.assertEqual(c2.config, c3.config) - - def test_custom(self): - config = Config() - config.foo = 'foo' - config.bar = 'bar' - c1 = Configurable(config=config) - c2 = Configurable(config=c1.config) - c3 = Configurable(config=c2.config) - self.assertEqual(c1.config, config) - self.assertEqual(c2.config, config) - self.assertEqual(c3.config, config) - # Test that copies are not made - self.assertTrue(c1.config is config) - self.assertTrue(c2.config is config) - self.assertTrue(c3.config is config) - self.assertTrue(c1.config is c2.config) - self.assertTrue(c2.config is c3.config) - - def test_inheritance(self): - config = Config() - config.MyConfigurable.a = 2 - config.MyConfigurable.b = 2.0 - c1 = MyConfigurable(config=config) - c2 = MyConfigurable(config=c1.config) - self.assertEqual(c1.a, config.MyConfigurable.a) - self.assertEqual(c1.b, config.MyConfigurable.b) - self.assertEqual(c2.a, config.MyConfigurable.a) - self.assertEqual(c2.b, config.MyConfigurable.b) - - def test_parent(self): - config = Config() - config.Foo.a = 10 - config.Foo.b = "wow" - config.Bar.b = 'later' - config.Bar.c = 100.0 - f = Foo(config=config) - b = Bar(config=f.config) - self.assertEqual(f.a, 10) - self.assertEqual(f.b, 'wow') - self.assertEqual(b.b, 'gotit') - self.assertEqual(b.c, 100.0) - - def test_override1(self): - config = Config() - config.MyConfigurable.a = 2 - config.MyConfigurable.b = 2.0 - c = MyConfigurable(a=3, config=config) - self.assertEqual(c.a, 3) - self.assertEqual(c.b, config.MyConfigurable.b) - self.assertEqual(c.c, 'no config') - - def test_override2(self): - config = Config() - config.Foo.a = 1 - config.Bar.b = 'or' # Up above b is config=False, so this won't do it. - config.Bar.c = 10.0 - c = Bar(config=config) - self.assertEqual(c.a, config.Foo.a) - self.assertEqual(c.b, 'gotit') - self.assertEqual(c.c, config.Bar.c) - c = Bar(a=2, b='and', c=20.0, config=config) - self.assertEqual(c.a, 2) - self.assertEqual(c.b, 'and') - self.assertEqual(c.c, 20.0) - - def test_help(self): - self.assertEqual(MyConfigurable.class_get_help(), mc_help) - - def test_help_inst(self): - inst = MyConfigurable(a=5, b=4) - self.assertEqual(MyConfigurable.class_get_help(inst), mc_help_inst) - - -class TestSingletonConfigurable(TestCase): - - def test_instance(self): - class Foo(SingletonConfigurable): pass - self.assertEqual(Foo.initialized(), False) - foo = Foo.instance() - self.assertEqual(Foo.initialized(), True) - self.assertEqual(foo, Foo.instance()) - self.assertEqual(SingletonConfigurable._instance, None) - - def test_inheritance(self): - class Bar(SingletonConfigurable): pass - class Bam(Bar): pass - self.assertEqual(Bar.initialized(), False) - self.assertEqual(Bam.initialized(), False) - bam = Bam.instance() - bam == Bar.instance() - self.assertEqual(Bar.initialized(), True) - self.assertEqual(Bam.initialized(), True) - self.assertEqual(bam, Bam._instance) - self.assertEqual(bam, Bar._instance) - self.assertEqual(SingletonConfigurable._instance, None) - - -class MyParent(Configurable): - pass - -class MyParent2(MyParent): - pass - -class TestParentConfigurable(TestCase): - - def test_parent_config(self): - cfg = Config({ - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 2.0, - } - } - }) - parent = MyParent(config=cfg) - myc = MyConfigurable(parent=parent) - self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) - - def test_parent_inheritance(self): - cfg = Config({ - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 2.0, - } - } - }) - parent = MyParent2(config=cfg) - myc = MyConfigurable(parent=parent) - self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) - - def test_multi_parent(self): - cfg = Config({ - 'MyParent2' : { - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 2.0, - } - }, - # this one shouldn't count - 'MyConfigurable' : { - 'b' : 3.0, - }, - } - }) - parent2 = MyParent2(config=cfg) - parent = MyParent(parent=parent2) - myc = MyConfigurable(parent=parent) - self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) - - def test_parent_priority(self): - cfg = Config({ - 'MyConfigurable' : { - 'b' : 2.0, - }, - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 3.0, - } - }, - 'MyParent2' : { - 'MyConfigurable' : { - 'b' : 4.0, - } - } - }) - parent = MyParent2(config=cfg) - myc = MyConfigurable(parent=parent) - self.assertEqual(myc.b, parent.config.MyParent2.MyConfigurable.b) - - def test_multi_parent_priority(self): - cfg = Config({ - 'MyConfigurable' : { - 'b' : 2.0, - }, - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 3.0, - } - }, - 'MyParent2' : { - 'MyConfigurable' : { - 'b' : 4.0, - } - }, - 'MyParent2' : { - 'MyParent' : { - 'MyConfigurable' : { - 'b' : 5.0, - } - } - } - }) - parent2 = MyParent2(config=cfg) - parent = MyParent2(parent=parent2) - myc = MyConfigurable(parent=parent) - self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) - -class Containers(Configurable): - lis = List(config=True) - def _lis_default(self): - return [-1] - - s = Set(config=True) - def _s_default(self): - return {'a'} - - d = Dict(config=True) - def _d_default(self): - return {'a' : 'b'} - -class TestConfigContainers(TestCase): - def test_extend(self): - c = Config() - c.Containers.lis.extend(list(range(5))) - obj = Containers(config=c) - self.assertEqual(obj.lis, list(range(-1,5))) - - def test_insert(self): - c = Config() - c.Containers.lis.insert(0, 'a') - c.Containers.lis.insert(1, 'b') - obj = Containers(config=c) - self.assertEqual(obj.lis, ['a', 'b', -1]) - - def test_prepend(self): - c = Config() - c.Containers.lis.prepend([1,2]) - c.Containers.lis.prepend([2,3]) - obj = Containers(config=c) - self.assertEqual(obj.lis, [2,3,1,2,-1]) - - def test_prepend_extend(self): - c = Config() - c.Containers.lis.prepend([1,2]) - c.Containers.lis.extend([2,3]) - obj = Containers(config=c) - self.assertEqual(obj.lis, [1,2,-1,2,3]) - - def test_append_extend(self): - c = Config() - c.Containers.lis.append([1,2]) - c.Containers.lis.extend([2,3]) - obj = Containers(config=c) - self.assertEqual(obj.lis, [-1,[1,2],2,3]) - - def test_extend_append(self): - c = Config() - c.Containers.lis.extend([2,3]) - c.Containers.lis.append([1,2]) - obj = Containers(config=c) - self.assertEqual(obj.lis, [-1,2,3,[1,2]]) - - def test_insert_extend(self): - c = Config() - c.Containers.lis.insert(0, 1) - c.Containers.lis.extend([2,3]) - obj = Containers(config=c) - self.assertEqual(obj.lis, [1,-1,2,3]) - - def test_set_update(self): - c = Config() - c.Containers.s.update({0,1,2}) - c.Containers.s.update({3}) - obj = Containers(config=c) - self.assertEqual(obj.s, {'a', 0, 1, 2, 3}) - - def test_dict_update(self): - c = Config() - c.Containers.d.update({'c' : 'd'}) - c.Containers.d.update({'e' : 'f'}) - obj = Containers(config=c) - self.assertEqual(obj.d, {'a':'b', 'c':'d', 'e':'f'}) - - def test_update_twice(self): - c = Config() - c.MyConfigurable.a = 5 - m = MyConfigurable(config=c) - self.assertEqual(m.a, 5) - - c2 = Config() - c2.MyConfigurable.a = 10 - m.update_config(c2) - self.assertEqual(m.a, 10) - - c2.MyConfigurable.a = 15 - m.update_config(c2) - self.assertEqual(m.a, 15) - - def test_config_default(self): - class SomeSingleton(SingletonConfigurable): - pass - - class DefaultConfigurable(Configurable): - a = Integer(config=True) - def _config_default(self): - if SomeSingleton.initialized(): - return SomeSingleton.instance().config - return Config() - - c = Config() - c.DefaultConfigurable.a = 5 - - d1 = DefaultConfigurable() - self.assertEqual(d1.a, 0) - - single = SomeSingleton.instance(config=c) - - d2 = DefaultConfigurable() - self.assertIs(d2.config, single.config) - self.assertEqual(d2.a, 5) - diff --git a/traitlets/config/tests/test_loader.py b/traitlets/config/tests/test_loader.py deleted file mode 100644 index 5c79ec1..0000000 --- a/traitlets/config/tests/test_loader.py +++ /dev/null @@ -1,419 +0,0 @@ -# encoding: utf-8 -"""Tests for traitlets.config.loader""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -import copy -import logging -import os -import pickle -import sys - -from tempfile import mkstemp -from unittest import TestCase - -from nose import SkipTest -import nose.tools as nt - - - -from traitlets.config.loader import ( - Config, - LazyConfigValue, - PyFileConfigLoader, - JSONFileConfigLoader, - KeyValueConfigLoader, - ArgParseConfigLoader, - KVArgParseConfigLoader, - ConfigError, -) - - -pyfile = """ -c = get_config() -c.a=10 -c.b=20 -c.Foo.Bar.value=10 -c.Foo.Bam.value=list(range(10)) -c.D.C.value='hi there' -""" - -json1file = """ -{ - "version": 1, - "a": 10, - "b": 20, - "Foo": { - "Bam": { - "value": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] - }, - "Bar": { - "value": 10 - } - }, - "D": { - "C": { - "value": "hi there" - } - } -} -""" - -# should not load -json2file = """ -{ - "version": 2 -} -""" - -import logging -log = logging.getLogger('devnull') -log.setLevel(0) - -class TestFileCL(TestCase): - - def _check_conf(self, config): - self.assertEqual(config.a, 10) - self.assertEqual(config.b, 20) - self.assertEqual(config.Foo.Bar.value, 10) - self.assertEqual(config.Foo.Bam.value, list(range(10))) - self.assertEqual(config.D.C.value, 'hi there') - - def test_python(self): - fd, fname = mkstemp('.py') - f = os.fdopen(fd, 'w') - f.write(pyfile) - f.close() - # Unlink the file - cl = PyFileConfigLoader(fname, log=log) - config = cl.load_config() - self._check_conf(config) - - def test_json(self): - fd, fname = mkstemp('.json') - f = os.fdopen(fd, 'w') - f.write(json1file) - f.close() - # Unlink the file - cl = JSONFileConfigLoader(fname, log=log) - config = cl.load_config() - self._check_conf(config) - - def test_collision(self): - a = Config() - b = Config() - self.assertEqual(a.collisions(b), {}) - a.A.trait1 = 1 - b.A.trait2 = 2 - self.assertEqual(a.collisions(b), {}) - b.A.trait1 = 1 - self.assertEqual(a.collisions(b), {}) - b.A.trait1 = 0 - self.assertEqual(a.collisions(b), { - 'A': { - 'trait1': "1 ignored, using 0", - } - }) - self.assertEqual(b.collisions(a), { - 'A': { - 'trait1': "0 ignored, using 1", - } - }) - a.A.trait2 = 3 - self.assertEqual(b.collisions(a), { - 'A': { - 'trait1': "0 ignored, using 1", - 'trait2': "2 ignored, using 3", - } - }) - - def test_v2raise(self): - fd, fname = mkstemp('.json') - f = os.fdopen(fd, 'w') - f.write(json2file) - f.close() - # Unlink the file - cl = JSONFileConfigLoader(fname, log=log) - with nt.assert_raises(ValueError): - cl.load_config() - - -class MyLoader1(ArgParseConfigLoader): - def _add_arguments(self, aliases=None, flags=None): - p = self.parser - p.add_argument('-f', '--foo', dest='Global.foo', type=str) - p.add_argument('-b', dest='MyClass.bar', type=int) - p.add_argument('-n', dest='n', action='store_true') - p.add_argument('Global.bam', type=str) - -class MyLoader2(ArgParseConfigLoader): - def _add_arguments(self, aliases=None, flags=None): - subparsers = self.parser.add_subparsers(dest='subparser_name') - subparser1 = subparsers.add_parser('1') - subparser1.add_argument('-x',dest='Global.x') - subparser2 = subparsers.add_parser('2') - subparser2.add_argument('y') - -class TestArgParseCL(TestCase): - - def test_basic(self): - cl = MyLoader1() - config = cl.load_config('-f hi -b 10 -n wow'.split()) - self.assertEqual(config.Global.foo, 'hi') - self.assertEqual(config.MyClass.bar, 10) - self.assertEqual(config.n, True) - self.assertEqual(config.Global.bam, 'wow') - config = cl.load_config(['wow']) - self.assertEqual(list(config.keys()), ['Global']) - self.assertEqual(list(config.Global.keys()), ['bam']) - self.assertEqual(config.Global.bam, 'wow') - - def test_add_arguments(self): - cl = MyLoader2() - config = cl.load_config('2 frobble'.split()) - self.assertEqual(config.subparser_name, '2') - self.assertEqual(config.y, 'frobble') - config = cl.load_config('1 -x frobble'.split()) - self.assertEqual(config.subparser_name, '1') - self.assertEqual(config.Global.x, 'frobble') - - def test_argv(self): - cl = MyLoader1(argv='-f hi -b 10 -n wow'.split()) - config = cl.load_config() - self.assertEqual(config.Global.foo, 'hi') - self.assertEqual(config.MyClass.bar, 10) - self.assertEqual(config.n, True) - self.assertEqual(config.Global.bam, 'wow') - - -class TestKeyValueCL(TestCase): - klass = KeyValueConfigLoader - - def test_eval(self): - cl = self.klass(log=log) - config = cl.load_config('--Class.str_trait=all --Class.int_trait=5 --Class.list_trait=["hello",5]'.split()) - self.assertEqual(config.Class.str_trait, 'all') - self.assertEqual(config.Class.int_trait, 5) - self.assertEqual(config.Class.list_trait, ["hello", 5]) - - def test_basic(self): - cl = self.klass(log=log) - argv = [ '--' + s[2:] for s in pyfile.split('\n') if s.startswith('c.') ] - print(argv) - config = cl.load_config(argv) - self.assertEqual(config.a, 10) - self.assertEqual(config.b, 20) - self.assertEqual(config.Foo.Bar.value, 10) - # non-literal expressions are not evaluated - self.assertEqual(config.Foo.Bam.value, 'list(range(10))') - self.assertEqual(config.D.C.value, 'hi there') - - def test_expanduser(self): - cl = self.klass(log=log) - argv = ['--a=~/1/2/3', '--b=~', '--c=~/', '--d="~/"'] - config = cl.load_config(argv) - self.assertEqual(config.a, os.path.expanduser('~/1/2/3')) - self.assertEqual(config.b, os.path.expanduser('~')) - self.assertEqual(config.c, os.path.expanduser('~/')) - self.assertEqual(config.d, '~/') - - def test_extra_args(self): - cl = self.klass(log=log) - config = cl.load_config(['--a=5', 'b', '--c=10', 'd']) - self.assertEqual(cl.extra_args, ['b', 'd']) - self.assertEqual(config.a, 5) - self.assertEqual(config.c, 10) - config = cl.load_config(['--', '--a=5', '--c=10']) - self.assertEqual(cl.extra_args, ['--a=5', '--c=10']) - - def test_unicode_args(self): - cl = self.klass(log=log) - argv = [u'--a=épsîlön'] - config = cl.load_config(argv) - self.assertEqual(config.a, u'épsîlön') - - def test_unicode_bytes_args(self): - uarg = u'--a=é' - try: - barg = uarg.encode(sys.stdin.encoding) - except (TypeError, UnicodeEncodeError): - raise SkipTest("sys.stdin.encoding can't handle 'é'") - - cl = self.klass(log=log) - config = cl.load_config([barg]) - self.assertEqual(config.a, u'é') - - def test_unicode_alias(self): - cl = self.klass(log=log) - argv = [u'--a=épsîlön'] - config = cl.load_config(argv, aliases=dict(a='A.a')) - self.assertEqual(config.A.a, u'épsîlön') - - -class TestArgParseKVCL(TestKeyValueCL): - klass = KVArgParseConfigLoader - - def test_expanduser2(self): - cl = self.klass(log=log) - argv = ['-a', '~/1/2/3', '--b', "'~/1/2/3'"] - config = cl.load_config(argv, aliases=dict(a='A.a', b='A.b')) - self.assertEqual(config.A.a, os.path.expanduser('~/1/2/3')) - self.assertEqual(config.A.b, '~/1/2/3') - - def test_eval(self): - cl = self.klass(log=log) - argv = ['-c', 'a=5'] - config = cl.load_config(argv, aliases=dict(c='A.c')) - self.assertEqual(config.A.c, u"a=5") - - -class TestConfig(TestCase): - - def test_setget(self): - c = Config() - c.a = 10 - self.assertEqual(c.a, 10) - self.assertEqual('b' in c, False) - - def test_auto_section(self): - c = Config() - self.assertNotIn('A', c) - assert not c._has_section('A') - A = c.A - A.foo = 'hi there' - self.assertIn('A', c) - assert c._has_section('A') - self.assertEqual(c.A.foo, 'hi there') - del c.A - self.assertEqual(c.A, Config()) - - def test_merge_doesnt_exist(self): - c1 = Config() - c2 = Config() - c2.bar = 10 - c2.Foo.bar = 10 - c1.merge(c2) - self.assertEqual(c1.Foo.bar, 10) - self.assertEqual(c1.bar, 10) - c2.Bar.bar = 10 - c1.merge(c2) - self.assertEqual(c1.Bar.bar, 10) - - def test_merge_exists(self): - c1 = Config() - c2 = Config() - c1.Foo.bar = 10 - c1.Foo.bam = 30 - c2.Foo.bar = 20 - c2.Foo.wow = 40 - c1.merge(c2) - self.assertEqual(c1.Foo.bam, 30) - self.assertEqual(c1.Foo.bar, 20) - self.assertEqual(c1.Foo.wow, 40) - c2.Foo.Bam.bam = 10 - c1.merge(c2) - self.assertEqual(c1.Foo.Bam.bam, 10) - - def test_deepcopy(self): - c1 = Config() - c1.Foo.bar = 10 - c1.Foo.bam = 30 - c1.a = 'asdf' - c1.b = range(10) - c1.Test.logger = logging.Logger('test') - c1.Test.get_logger = logging.getLogger('test') - c2 = copy.deepcopy(c1) - self.assertEqual(c1, c2) - self.assertTrue(c1 is not c2) - self.assertTrue(c1.Foo is not c2.Foo) - self.assertTrue(c1.Test is not c2.Test) - self.assertTrue(c1.Test.logger is c2.Test.logger) - self.assertTrue(c1.Test.get_logger is c2.Test.get_logger) - - def test_builtin(self): - c1 = Config() - c1.format = "json" - - def test_fromdict(self): - c1 = Config({'Foo' : {'bar' : 1}}) - self.assertEqual(c1.Foo.__class__, Config) - self.assertEqual(c1.Foo.bar, 1) - - def test_fromdictmerge(self): - c1 = Config() - c2 = Config({'Foo' : {'bar' : 1}}) - c1.merge(c2) - self.assertEqual(c1.Foo.__class__, Config) - self.assertEqual(c1.Foo.bar, 1) - - def test_fromdictmerge2(self): - c1 = Config({'Foo' : {'baz' : 2}}) - c2 = Config({'Foo' : {'bar' : 1}}) - c1.merge(c2) - self.assertEqual(c1.Foo.__class__, Config) - self.assertEqual(c1.Foo.bar, 1) - self.assertEqual(c1.Foo.baz, 2) - self.assertNotIn('baz', c2.Foo) - - def test_contains(self): - c1 = Config({'Foo' : {'baz' : 2}}) - c2 = Config({'Foo' : {'bar' : 1}}) - self.assertIn('Foo', c1) - self.assertIn('Foo.baz', c1) - self.assertIn('Foo.bar', c2) - self.assertNotIn('Foo.bar', c1) - - def test_pickle_config(self): - cfg = Config() - cfg.Foo.bar = 1 - pcfg = pickle.dumps(cfg) - cfg2 = pickle.loads(pcfg) - self.assertEqual(cfg2, cfg) - - def test_getattr_section(self): - cfg = Config() - self.assertNotIn('Foo', cfg) - Foo = cfg.Foo - assert isinstance(Foo, Config) - self.assertIn('Foo', cfg) - - def test_getitem_section(self): - cfg = Config() - self.assertNotIn('Foo', cfg) - Foo = cfg['Foo'] - assert isinstance(Foo, Config) - self.assertIn('Foo', cfg) - - def test_getattr_not_section(self): - cfg = Config() - self.assertNotIn('foo', cfg) - foo = cfg.foo - assert isinstance(foo, LazyConfigValue) - self.assertIn('foo', cfg) - - def test_getattr_private_missing(self): - cfg = Config() - self.assertNotIn('_repr_html_', cfg) - with self.assertRaises(AttributeError): - _ = cfg._repr_html_ - self.assertNotIn('_repr_html_', cfg) - self.assertEqual(len(cfg), 0) - - def test_getitem_not_section(self): - cfg = Config() - self.assertNotIn('foo', cfg) - foo = cfg['foo'] - assert isinstance(foo, LazyConfigValue) - self.assertIn('foo', cfg) - - def test_merge_copies(self): - c = Config() - c2 = Config() - c2.Foo.trait = [] - c.merge(c2) - c2.Foo.trait.append(1) - self.assertIsNot(c.Foo, c2.Foo) - self.assertEqual(c.Foo.trait, []) - self.assertEqual(c2.Foo.trait, [1]) - diff --git a/traitlets/getargspec.py b/traitlets/getargspec.py deleted file mode 100644 index 6f33ec2..0000000 --- a/traitlets/getargspec.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -""" - getargspec excerpted from: - - sphinx.util.inspect - ~~~~~~~~~~~~~~~~~~~ - Helpers for inspecting Python modules. - :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import inspect -from IPython.utils.py3compat import PY3 - -# Unmodified from sphinx below this line - -if PY3: - from functools import partial - - def getargspec(func): - """Like inspect.getargspec but supports functools.partial as well.""" - if inspect.ismethod(func): - func = func.__func__ - if type(func) is partial: - orig_func = func.func - argspec = getargspec(orig_func) - args = list(argspec[0]) - defaults = list(argspec[3] or ()) - kwoargs = list(argspec[4]) - kwodefs = dict(argspec[5] or {}) - if func.args: - args = args[len(func.args):] - for arg in func.keywords or (): - try: - i = args.index(arg) - len(args) - del args[i] - try: - del defaults[i] - except IndexError: - pass - except ValueError: # must be a kwonly arg - i = kwoargs.index(arg) - del kwoargs[i] - del kwodefs[arg] - return inspect.FullArgSpec(args, argspec[1], argspec[2], - tuple(defaults), kwoargs, - kwodefs, argspec[6]) - while hasattr(func, '__wrapped__'): - func = func.__wrapped__ - if not inspect.isfunction(func): - raise TypeError('%r is not a Python function' % func) - return inspect.getfullargspec(func) - -else: # 2.6, 2.7 - from functools import partial - - def getargspec(func): - """Like inspect.getargspec but supports functools.partial as well.""" - if inspect.ismethod(func): - func = func.__func__ - parts = 0, () - if type(func) is partial: - keywords = func.keywords - if keywords is None: - keywords = {} - parts = len(func.args), keywords.keys() - func = func.func - if not inspect.isfunction(func): - raise TypeError('%r is not a Python function' % func) - args, varargs, varkw = inspect.getargs(func.__code__) - func_defaults = func.__defaults__ - if func_defaults is None: - func_defaults = [] - else: - func_defaults = list(func_defaults) - if parts[0]: - args = args[parts[0]:] - if parts[1]: - for arg in parts[1]: - i = args.index(arg) - len(args) - del args[i] - try: - del func_defaults[i] - except IndexError: - pass - return inspect.ArgSpec(args, varargs, varkw, func_defaults) diff --git a/traitlets/log.py b/traitlets/log.py deleted file mode 100644 index 4ebc5a9..0000000 --- a/traitlets/log.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Grab the global logger instance.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -import logging - -_logger = None - -def get_logger(): - """Grab the global logger instance. - - If a global Application is instantiated, grab its logger. - Otherwise, grab the root logger. - """ - global _logger - - if _logger is None: - from .config import Application - if Application.initialized(): - _logger = Application.instance().log - else: - logging.basicConfig() - _logger = logging.getLogger() - return _logger diff --git a/traitlets/sentinel.py b/traitlets/sentinel.py deleted file mode 100644 index dc57a25..0000000 --- a/traitlets/sentinel.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Sentinel class for constants with useful reprs""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -class Sentinel(object): - - def __init__(self, name, module, docstring=None): - self.name = name - self.module = module - if docstring: - self.__doc__ = docstring - - - def __repr__(self): - return str(self.module)+'.'+self.name - diff --git a/traitlets/tests/__init__.py b/traitlets/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/traitlets/tests/__init__.py +++ /dev/null diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py deleted file mode 100644 index 9ba9122..0000000 --- a/traitlets/tests/test_traitlets.py +++ /dev/null @@ -1,1591 +0,0 @@ -# encoding: utf-8 -"""Tests for IPython.utils.traitlets.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. -# -# Adapted from enthought.traits, Copyright (c) Enthought, Inc., -# also under the terms of the Modified BSD License. - -import pickle -import re -import sys -from unittest import TestCase - -import nose.tools as nt -from nose import SkipTest - -from IPython.utils.traitlets import ( - HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum, - Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError, - Union, Undefined, Type, This, Instance, TCPAddress, List, Tuple, - ObjectName, DottedObjectName, CRegExp, link, directional_link, - ForwardDeclaredType, ForwardDeclaredInstance, -) -from IPython.utils import py3compat -from IPython.testing.decorators import skipif - -#----------------------------------------------------------------------------- -# Helper classes for testing -#----------------------------------------------------------------------------- - - -class HasTraitsStub(HasTraits): - - def _notify_trait(self, name, old, new): - self._notify_name = name - self._notify_old = old - self._notify_new = new - - -#----------------------------------------------------------------------------- -# Test classes -#----------------------------------------------------------------------------- - - -class TestTraitType(TestCase): - - def test_get_undefined(self): - class A(HasTraits): - a = TraitType - a = A() - self.assertEqual(a.a, Undefined) - - def test_set(self): - class A(HasTraitsStub): - a = TraitType - - a = A() - a.a = 10 - self.assertEqual(a.a, 10) - self.assertEqual(a._notify_name, 'a') - self.assertEqual(a._notify_old, Undefined) - self.assertEqual(a._notify_new, 10) - - def test_validate(self): - class MyTT(TraitType): - def validate(self, inst, value): - return -1 - class A(HasTraitsStub): - tt = MyTT - - a = A() - a.tt = 10 - self.assertEqual(a.tt, -1) - - def test_default_validate(self): - class MyIntTT(TraitType): - def validate(self, obj, value): - if isinstance(value, int): - return value - self.error(obj, value) - class A(HasTraits): - tt = MyIntTT(10) - a = A() - self.assertEqual(a.tt, 10) - - # Defaults are validated when the HasTraits is instantiated - class B(HasTraits): - tt = MyIntTT('bad default') - self.assertRaises(TraitError, B) - - def test_info(self): - class A(HasTraits): - tt = TraitType - a = A() - self.assertEqual(A.tt.info(), 'any value') - - def test_error(self): - class A(HasTraits): - tt = TraitType - a = A() - self.assertRaises(TraitError, A.tt.error, a, 10) - - def test_dynamic_initializer(self): - class A(HasTraits): - x = Int(10) - def _x_default(self): - return 11 - class B(A): - x = Int(20) - class C(A): - def _x_default(self): - return 21 - - a = A() - self.assertEqual(a._trait_values, {}) - self.assertEqual(list(a._trait_dyn_inits.keys()), ['x']) - self.assertEqual(a.x, 11) - self.assertEqual(a._trait_values, {'x': 11}) - b = B() - self.assertEqual(b._trait_values, {'x': 20}) - self.assertEqual(list(a._trait_dyn_inits.keys()), ['x']) - self.assertEqual(b.x, 20) - c = C() - self.assertEqual(c._trait_values, {}) - self.assertEqual(list(a._trait_dyn_inits.keys()), ['x']) - self.assertEqual(c.x, 21) - self.assertEqual(c._trait_values, {'x': 21}) - # Ensure that the base class remains unmolested when the _default - # initializer gets overridden in a subclass. - a = A() - c = C() - self.assertEqual(a._trait_values, {}) - self.assertEqual(list(a._trait_dyn_inits.keys()), ['x']) - self.assertEqual(a.x, 11) - self.assertEqual(a._trait_values, {'x': 11}) - - - -class TestHasTraitsMeta(TestCase): - - def test_metaclass(self): - self.assertEqual(type(HasTraits), MetaHasTraits) - - class A(HasTraits): - a = Int - - a = A() - self.assertEqual(type(a.__class__), MetaHasTraits) - self.assertEqual(a.a,0) - a.a = 10 - self.assertEqual(a.a,10) - - class B(HasTraits): - b = Int() - - b = B() - self.assertEqual(b.b,0) - b.b = 10 - self.assertEqual(b.b,10) - - class C(HasTraits): - c = Int(30) - - c = C() - self.assertEqual(c.c,30) - c.c = 10 - self.assertEqual(c.c,10) - - def test_this_class(self): - class A(HasTraits): - t = This() - tt = This() - class B(A): - tt = This() - ttt = This() - self.assertEqual(A.t.this_class, A) - self.assertEqual(B.t.this_class, A) - self.assertEqual(B.tt.this_class, B) - self.assertEqual(B.ttt.this_class, B) - -class TestHasTraitsNotify(TestCase): - - def setUp(self): - self._notify1 = [] - self._notify2 = [] - - def notify1(self, name, old, new): - self._notify1.append((name, old, new)) - - def notify2(self, name, old, new): - self._notify2.append((name, old, new)) - - def test_notify_all(self): - - class A(HasTraits): - a = Int - b = Float - - a = A() - a.on_trait_change(self.notify1) - a.a = 0 - self.assertEqual(len(self._notify1),0) - a.b = 0.0 - self.assertEqual(len(self._notify1),0) - a.a = 10 - self.assertTrue(('a',0,10) in self._notify1) - a.b = 10.0 - self.assertTrue(('b',0.0,10.0) in self._notify1) - self.assertRaises(TraitError,setattr,a,'a','bad string') - self.assertRaises(TraitError,setattr,a,'b','bad string') - self._notify1 = [] - a.on_trait_change(self.notify1,remove=True) - a.a = 20 - a.b = 20.0 - self.assertEqual(len(self._notify1),0) - - def test_notify_one(self): - - class A(HasTraits): - a = Int - b = Float - - a = A() - a.on_trait_change(self.notify1, 'a') - a.a = 0 - self.assertEqual(len(self._notify1),0) - a.a = 10 - self.assertTrue(('a',0,10) in self._notify1) - self.assertRaises(TraitError,setattr,a,'a','bad string') - - def test_subclass(self): - - class A(HasTraits): - a = Int - - class B(A): - b = Float - - b = B() - self.assertEqual(b.a,0) - self.assertEqual(b.b,0.0) - b.a = 100 - b.b = 100.0 - self.assertEqual(b.a,100) - self.assertEqual(b.b,100.0) - - def test_notify_subclass(self): - - class A(HasTraits): - a = Int - - class B(A): - b = Float - - b = B() - b.on_trait_change(self.notify1, 'a') - b.on_trait_change(self.notify2, 'b') - b.a = 0 - b.b = 0.0 - self.assertEqual(len(self._notify1),0) - self.assertEqual(len(self._notify2),0) - b.a = 10 - b.b = 10.0 - self.assertTrue(('a',0,10) in self._notify1) - self.assertTrue(('b',0.0,10.0) in self._notify2) - - def test_static_notify(self): - - class A(HasTraits): - a = Int - _notify1 = [] - def _a_changed(self, name, old, new): - self._notify1.append((name, old, new)) - - a = A() - a.a = 0 - # This is broken!!! - self.assertEqual(len(a._notify1),0) - a.a = 10 - self.assertTrue(('a',0,10) in a._notify1) - - class B(A): - b = Float - _notify2 = [] - def _b_changed(self, name, old, new): - self._notify2.append((name, old, new)) - - b = B() - b.a = 10 - b.b = 10.0 - self.assertTrue(('a',0,10) in b._notify1) - self.assertTrue(('b',0.0,10.0) in b._notify2) - - def test_notify_args(self): - - def callback0(): - self.cb = () - def callback1(name): - self.cb = (name,) - def callback2(name, new): - self.cb = (name, new) - def callback3(name, old, new): - self.cb = (name, old, new) - - class A(HasTraits): - a = Int - - a = A() - a.on_trait_change(callback0, 'a') - a.a = 10 - self.assertEqual(self.cb,()) - a.on_trait_change(callback0, 'a', remove=True) - - a.on_trait_change(callback1, 'a') - a.a = 100 - self.assertEqual(self.cb,('a',)) - a.on_trait_change(callback1, 'a', remove=True) - - a.on_trait_change(callback2, 'a') - a.a = 1000 - self.assertEqual(self.cb,('a',1000)) - a.on_trait_change(callback2, 'a', remove=True) - - a.on_trait_change(callback3, 'a') - a.a = 10000 - self.assertEqual(self.cb,('a',1000,10000)) - a.on_trait_change(callback3, 'a', remove=True) - - self.assertEqual(len(a._trait_notifiers['a']),0) - - def test_notify_only_once(self): - - class A(HasTraits): - listen_to = ['a'] - - a = Int(0) - b = 0 - - def __init__(self, **kwargs): - super(A, self).__init__(**kwargs) - self.on_trait_change(self.listener1, ['a']) - - def listener1(self, name, old, new): - self.b += 1 - - class B(A): - - c = 0 - d = 0 - - def __init__(self, **kwargs): - super(B, self).__init__(**kwargs) - self.on_trait_change(self.listener2) - - def listener2(self, name, old, new): - self.c += 1 - - def _a_changed(self, name, old, new): - self.d += 1 - - b = B() - b.a += 1 - self.assertEqual(b.b, b.c) - self.assertEqual(b.b, b.d) - b.a += 1 - self.assertEqual(b.b, b.c) - self.assertEqual(b.b, b.d) - - -class TestHasTraits(TestCase): - - def test_trait_names(self): - class A(HasTraits): - i = Int - f = Float - a = A() - self.assertEqual(sorted(a.trait_names()),['f','i']) - self.assertEqual(sorted(A.class_trait_names()),['f','i']) - - def test_trait_metadata(self): - class A(HasTraits): - i = Int(config_key='MY_VALUE') - a = A() - self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE') - - def test_trait_metadata_default(self): - class A(HasTraits): - i = Int() - a = A() - self.assertEqual(a.trait_metadata('i', 'config_key'), None) - self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default') - - def test_traits(self): - class A(HasTraits): - i = Int - f = Float - a = A() - self.assertEqual(a.traits(), dict(i=A.i, f=A.f)) - self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f)) - - def test_traits_metadata(self): - class A(HasTraits): - i = Int(config_key='VALUE1', other_thing='VALUE2') - f = Float(config_key='VALUE3', other_thing='VALUE2') - j = Int(0) - a = A() - self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j)) - traits = a.traits(config_key='VALUE1', other_thing='VALUE2') - self.assertEqual(traits, dict(i=A.i)) - - # This passes, but it shouldn't because I am replicating a bug in - # traits. - traits = a.traits(config_key=lambda v: True) - self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j)) - - def test_init(self): - class A(HasTraits): - i = Int() - x = Float() - a = A(i=1, x=10.0) - self.assertEqual(a.i, 1) - self.assertEqual(a.x, 10.0) - - def test_positional_args(self): - class A(HasTraits): - i = Int(0) - def __init__(self, i): - super(A, self).__init__() - self.i = i - - a = A(5) - self.assertEqual(a.i, 5) - # should raise TypeError if no positional arg given - self.assertRaises(TypeError, A) - -#----------------------------------------------------------------------------- -# Tests for specific trait types -#----------------------------------------------------------------------------- - - -class TestType(TestCase): - - def test_default(self): - - class B(object): pass - class A(HasTraits): - klass = Type(allow_none=True) - - a = A() - self.assertEqual(a.klass, None) - - a.klass = B - self.assertEqual(a.klass, B) - self.assertRaises(TraitError, setattr, a, 'klass', 10) - - def test_value(self): - - class B(object): pass - class C(object): pass - class A(HasTraits): - klass = Type(B) - - a = A() - self.assertEqual(a.klass, B) - self.assertRaises(TraitError, setattr, a, 'klass', C) - self.assertRaises(TraitError, setattr, a, 'klass', object) - a.klass = B - - def test_allow_none(self): - - class B(object): pass - class C(B): pass - class A(HasTraits): - klass = Type(B) - - a = A() - self.assertEqual(a.klass, B) - self.assertRaises(TraitError, setattr, a, 'klass', None) - a.klass = C - self.assertEqual(a.klass, C) - - def test_validate_klass(self): - - class A(HasTraits): - klass = Type('no strings allowed') - - self.assertRaises(ImportError, A) - - class A(HasTraits): - klass = Type('rub.adub.Duck') - - self.assertRaises(ImportError, A) - - def test_validate_default(self): - - class B(object): pass - class A(HasTraits): - klass = Type('bad default', B) - - self.assertRaises(ImportError, A) - - class C(HasTraits): - klass = Type(None, B) - - self.assertRaises(TraitError, C) - - def test_str_klass(self): - - class A(HasTraits): - klass = Type('IPython.utils.ipstruct.Struct') - - from IPython.utils.ipstruct import Struct - a = A() - a.klass = Struct - self.assertEqual(a.klass, Struct) - - self.assertRaises(TraitError, setattr, a, 'klass', 10) - - def test_set_str_klass(self): - - class A(HasTraits): - klass = Type() - - a = A(klass='IPython.utils.ipstruct.Struct') - from IPython.utils.ipstruct import Struct - self.assertEqual(a.klass, Struct) - -class TestInstance(TestCase): - - def test_basic(self): - class Foo(object): pass - class Bar(Foo): pass - class Bah(object): pass - - class A(HasTraits): - inst = Instance(Foo, allow_none=True) - - a = A() - self.assertTrue(a.inst is None) - a.inst = Foo() - self.assertTrue(isinstance(a.inst, Foo)) - a.inst = Bar() - self.assertTrue(isinstance(a.inst, Foo)) - self.assertRaises(TraitError, setattr, a, 'inst', Foo) - self.assertRaises(TraitError, setattr, a, 'inst', Bar) - self.assertRaises(TraitError, setattr, a, 'inst', Bah()) - - def test_default_klass(self): - class Foo(object): pass - class Bar(Foo): pass - class Bah(object): pass - - class FooInstance(Instance): - klass = Foo - - class A(HasTraits): - inst = FooInstance(allow_none=True) - - a = A() - self.assertTrue(a.inst is None) - a.inst = Foo() - self.assertTrue(isinstance(a.inst, Foo)) - a.inst = Bar() - self.assertTrue(isinstance(a.inst, Foo)) - self.assertRaises(TraitError, setattr, a, 'inst', Foo) - self.assertRaises(TraitError, setattr, a, 'inst', Bar) - self.assertRaises(TraitError, setattr, a, 'inst', Bah()) - - def test_unique_default_value(self): - class Foo(object): pass - class A(HasTraits): - inst = Instance(Foo,(),{}) - - a = A() - b = A() - self.assertTrue(a.inst is not b.inst) - - def test_args_kw(self): - class Foo(object): - def __init__(self, c): self.c = c - class Bar(object): pass - class Bah(object): - def __init__(self, c, d): - self.c = c; self.d = d - - class A(HasTraits): - inst = Instance(Foo, (10,)) - a = A() - self.assertEqual(a.inst.c, 10) - - class B(HasTraits): - inst = Instance(Bah, args=(10,), kw=dict(d=20)) - b = B() - self.assertEqual(b.inst.c, 10) - self.assertEqual(b.inst.d, 20) - - class C(HasTraits): - inst = Instance(Foo, allow_none=True) - c = C() - self.assertTrue(c.inst is None) - - def test_bad_default(self): - class Foo(object): pass - - class A(HasTraits): - inst = Instance(Foo) - - self.assertRaises(TraitError, A) - - def test_instance(self): - class Foo(object): pass - - def inner(): - class A(HasTraits): - inst = Instance(Foo()) - - self.assertRaises(TraitError, inner) - - -class TestThis(TestCase): - - def test_this_class(self): - class Foo(HasTraits): - this = This - - f = Foo() - self.assertEqual(f.this, None) - g = Foo() - f.this = g - self.assertEqual(f.this, g) - self.assertRaises(TraitError, setattr, f, 'this', 10) - - def test_this_inst(self): - class Foo(HasTraits): - this = This() - - f = Foo() - f.this = Foo() - self.assertTrue(isinstance(f.this, Foo)) - - def test_subclass(self): - class Foo(HasTraits): - t = This() - class Bar(Foo): - pass - f = Foo() - b = Bar() - f.t = b - b.t = f - self.assertEqual(f.t, b) - self.assertEqual(b.t, f) - - def test_subclass_override(self): - class Foo(HasTraits): - t = This() - class Bar(Foo): - t = This() - f = Foo() - b = Bar() - f.t = b - self.assertEqual(f.t, b) - self.assertRaises(TraitError, setattr, b, 't', f) - - def test_this_in_container(self): - - class Tree(HasTraits): - value = Unicode() - leaves = List(This()) - - tree = Tree( - value='foo', - leaves=[Tree('bar'), Tree('buzz')] - ) - - with self.assertRaises(TraitError): - tree.leaves = [1, 2] - -class TraitTestBase(TestCase): - """A best testing class for basic trait types.""" - - def assign(self, value): - self.obj.value = value - - def coerce(self, value): - return value - - def test_good_values(self): - if hasattr(self, '_good_values'): - for value in self._good_values: - self.assign(value) - self.assertEqual(self.obj.value, self.coerce(value)) - - def test_bad_values(self): - if hasattr(self, '_bad_values'): - for value in self._bad_values: - try: - self.assertRaises(TraitError, self.assign, value) - except AssertionError: - assert False, value - - def test_default_value(self): - if hasattr(self, '_default_value'): - self.assertEqual(self._default_value, self.obj.value) - - def test_allow_none(self): - if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and - None in self._bad_values): - trait=self.obj.traits()['value'] - try: - trait.allow_none = True - self._bad_values.remove(None) - #skip coerce. Allow None casts None to None. - self.assign(None) - self.assertEqual(self.obj.value,None) - self.test_good_values() - self.test_bad_values() - finally: - #tear down - trait.allow_none = False - self._bad_values.append(None) - - def tearDown(self): - # restore default value after tests, if set - if hasattr(self, '_default_value'): - self.obj.value = self._default_value - - -class AnyTrait(HasTraits): - - value = Any - -class AnyTraitTest(TraitTestBase): - - obj = AnyTrait() - - _default_value = None - _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j] - _bad_values = [] - -class UnionTrait(HasTraits): - - value = Union([Type(), Bool()]) - -class UnionTraitTest(TraitTestBase): - - obj = UnionTrait(value='IPython.utils.ipstruct.Struct') - _good_values = [int, float, True] - _bad_values = [[], (0,), 1j] - -class OrTrait(HasTraits): - - value = Bool() | Unicode() - -class OrTraitTest(TraitTestBase): - - obj = OrTrait() - _good_values = [True, False, 'ten'] - _bad_values = [[], (0,), 1j] - -class IntTrait(HasTraits): - - value = Int(99) - -class TestInt(TraitTestBase): - - obj = IntTrait() - _default_value = 99 - _good_values = [10, -10] - _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j, - 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L', - u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10'] - if not py3compat.PY3: - _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint]) - - -class LongTrait(HasTraits): - - value = Long(99 if py3compat.PY3 else long(99)) - -class TestLong(TraitTestBase): - - obj = LongTrait() - - _default_value = 99 if py3compat.PY3 else long(99) - _good_values = [10, -10] - _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), - None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1', - '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1', - u'-10.1'] - if not py3compat.PY3: - # maxint undefined on py3, because int == long - _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint]) - _bad_values.extend([[long(10)], (long(10),)]) - - @skipif(py3compat.PY3, "not relevant on py3") - def test_cast_small(self): - """Long casts ints to long""" - self.obj.value = 10 - self.assertEqual(type(self.obj.value), long) - - -class IntegerTrait(HasTraits): - value = Integer(1) - -class TestInteger(TestLong): - obj = IntegerTrait() - _default_value = 1 - - def coerce(self, n): - return int(n) - - @skipif(py3compat.PY3, "not relevant on py3") - def test_cast_small(self): - """Integer casts small longs to int""" - if py3compat.PY3: - raise SkipTest("not relevant on py3") - - self.obj.value = long(100) - self.assertEqual(type(self.obj.value), int) - - -class FloatTrait(HasTraits): - - value = Float(99.0) - -class TestFloat(TraitTestBase): - - obj = FloatTrait() - - _default_value = 99.0 - _good_values = [10, -10, 10.1, -10.1] - _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, - 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10', - u'-10', u'10L', u'-10L', u'10.1', u'-10.1'] - if not py3compat.PY3: - _bad_values.extend([long(10), long(-10)]) - - -class ComplexTrait(HasTraits): - - value = Complex(99.0-99.0j) - -class TestComplex(TraitTestBase): - - obj = ComplexTrait() - - _default_value = 99.0-99.0j - _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j, - 10.1j, 10.1+10.1j, 10.1-10.1j] - _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None] - if not py3compat.PY3: - _bad_values.extend([long(10), long(-10)]) - - -class BytesTrait(HasTraits): - - value = Bytes(b'string') - -class TestBytes(TraitTestBase): - - obj = BytesTrait() - - _default_value = b'string' - _good_values = [b'10', b'-10', b'10L', - b'-10L', b'10.1', b'-10.1', b'string'] - _bad_values = [10, -10, 10.1, -10.1, 1j, [10], - ['ten'],{'ten': 10},(10,), None, u'string'] - if not py3compat.PY3: - _bad_values.extend([long(10), long(-10)]) - - -class UnicodeTrait(HasTraits): - - value = Unicode(u'unicode') - -class TestUnicode(TraitTestBase): - - obj = UnicodeTrait() - - _default_value = u'unicode' - _good_values = ['10', '-10', '10L', '-10L', '10.1', - '-10.1', '', u'', 'string', u'string', u"€"] - _bad_values = [10, -10, 10.1, -10.1, 1j, - [10], ['ten'], [u'ten'], {'ten': 10},(10,), None] - if not py3compat.PY3: - _bad_values.extend([long(10), long(-10)]) - - -class ObjectNameTrait(HasTraits): - value = ObjectName("abc") - -class TestObjectName(TraitTestBase): - obj = ObjectNameTrait() - - _default_value = "abc" - _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"] - _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]", - None, object(), object] - if sys.version_info[0] < 3: - _bad_values.append(u"þ") - else: - _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131). - - -class DottedObjectNameTrait(HasTraits): - value = DottedObjectName("a.b") - -class TestDottedObjectName(TraitTestBase): - obj = DottedObjectNameTrait() - - _default_value = "a.b" - _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"] - _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None] - if sys.version_info[0] < 3: - _bad_values.append(u"t.þ") - else: - _good_values.append(u"t.þ") - - -class TCPAddressTrait(HasTraits): - value = TCPAddress() - -class TestTCPAddress(TraitTestBase): - - obj = TCPAddressTrait() - - _default_value = ('127.0.0.1',0) - _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)] - _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None] - -class ListTrait(HasTraits): - - value = List(Int) - -class TestList(TraitTestBase): - - obj = ListTrait() - - _default_value = [] - _good_values = [[], [1], list(range(10)), (1,2)] - _bad_values = [10, [1,'a'], 'a'] - - def coerce(self, value): - if value is not None: - value = list(value) - return value - -class Foo(object): - pass - -class NoneInstanceListTrait(HasTraits): - - value = List(Instance(Foo)) - -class TestNoneInstanceList(TraitTestBase): - - obj = NoneInstanceListTrait() - - _default_value = [] - _good_values = [[Foo(), Foo()], []] - _bad_values = [[None], [Foo(), None]] - - -class InstanceListTrait(HasTraits): - - value = List(Instance(__name__+'.Foo')) - -class TestInstanceList(TraitTestBase): - - obj = InstanceListTrait() - - def test_klass(self): - """Test that the instance klass is properly assigned.""" - self.assertIs(self.obj.traits()['value']._trait.klass, Foo) - - _default_value = [] - _good_values = [[Foo(), Foo()], []] - _bad_values = [['1', 2,], '1', [Foo], None] - -class UnionListTrait(HasTraits): - - value = List(Int() | Bool()) - -class TestUnionListTrait(HasTraits): - - obj = UnionListTrait() - - _default_value = [] - _good_values = [[True, 1], [False, True]] - _bad_values = [[1, 'True'], False] - - -class LenListTrait(HasTraits): - - value = List(Int, [0], minlen=1, maxlen=2) - -class TestLenList(TraitTestBase): - - obj = LenListTrait() - - _default_value = [0] - _good_values = [[1], [1,2], (1,2)] - _bad_values = [10, [1,'a'], 'a', [], list(range(3))] - - def coerce(self, value): - if value is not None: - value = list(value) - return value - -class TupleTrait(HasTraits): - - value = Tuple(Int(allow_none=True), default_value=(1,)) - -class TestTupleTrait(TraitTestBase): - - obj = TupleTrait() - - _default_value = (1,) - _good_values = [(1,), (0,), [1]] - _bad_values = [10, (1, 2), ('a'), (), None] - - def coerce(self, value): - if value is not None: - value = tuple(value) - return value - - def test_invalid_args(self): - self.assertRaises(TypeError, Tuple, 5) - self.assertRaises(TypeError, Tuple, default_value='hello') - t = Tuple(Int, CBytes, default_value=(1,5)) - -class LooseTupleTrait(HasTraits): - - value = Tuple((1,2,3)) - -class TestLooseTupleTrait(TraitTestBase): - - obj = LooseTupleTrait() - - _default_value = (1,2,3) - _good_values = [(1,), [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()] - _bad_values = [10, 'hello', {}, None] - - def coerce(self, value): - if value is not None: - value = tuple(value) - return value - - def test_invalid_args(self): - self.assertRaises(TypeError, Tuple, 5) - self.assertRaises(TypeError, Tuple, default_value='hello') - t = Tuple(Int, CBytes, default_value=(1,5)) - - -class MultiTupleTrait(HasTraits): - - value = Tuple(Int, Bytes, default_value=[99,b'bottles']) - -class TestMultiTuple(TraitTestBase): - - obj = MultiTupleTrait() - - _default_value = (99,b'bottles') - _good_values = [(1,b'a'), (2,b'b')] - _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a')) - -class CRegExpTrait(HasTraits): - - value = CRegExp(r'') - -class TestCRegExp(TraitTestBase): - - def coerce(self, value): - return re.compile(value) - - obj = CRegExpTrait() - - _default_value = re.compile(r'') - _good_values = [r'\d+', re.compile(r'\d+')] - _bad_values = ['(', None, ()] - -class DictTrait(HasTraits): - value = Dict() - -def test_dict_assignment(): - d = dict() - c = DictTrait() - c.value = d - d['a'] = 5 - nt.assert_equal(d, c.value) - nt.assert_true(c.value is d) - -class ValidatedDictTrait(HasTraits): - - value = Dict(Unicode()) - -class TestInstanceDict(TraitTestBase): - - obj = ValidatedDictTrait() - - _default_value = {} - _good_values = [{'0': 'foo'}, {'1': 'bar'}] - _bad_values = [{'0': 0}, {'1': 1}] - - -def test_dict_default_value(): - """Check that the `{}` default value of the Dict traitlet constructor is - actually copied.""" - - d1, d2 = Dict(), Dict() - nt.assert_false(d1.get_default_value() is d2.get_default_value()) - - -class TestValidationHook(TestCase): - - def test_parity_trait(self): - """Verify that the early validation hook is effective""" - - class Parity(HasTraits): - - value = Int(0) - parity = Enum(['odd', 'even'], default_value='even') - - def _value_validate(self, value, trait): - if self.parity == 'even' and value % 2: - raise TraitError('Expected an even number') - if self.parity == 'odd' and (value % 2 == 0): - raise TraitError('Expected an odd number') - return value - - u = Parity() - u.parity = 'odd' - u.value = 1 # OK - with self.assertRaises(TraitError): - u.value = 2 # Trait Error - - u.parity = 'even' - u.value = 2 # OK - - -class TestLink(TestCase): - - def test_connect_same(self): - """Verify two traitlets of the same type can be linked together using link.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - a = A(value=9) - b = A(value=8) - - # Conenct the two classes. - c = link((a, 'value'), (b, 'value')) - - # Make sure the values are the same at the point of linking. - self.assertEqual(a.value, b.value) - - # Change one of the values to make sure they stay in sync. - a.value = 5 - self.assertEqual(a.value, b.value) - b.value = 6 - self.assertEqual(a.value, b.value) - - def test_link_different(self): - """Verify two traitlets of different types can be linked together using link.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - class B(HasTraits): - count = Int() - a = A(value=9) - b = B(count=8) - - # Conenct the two classes. - c = link((a, 'value'), (b, 'count')) - - # Make sure the values are the same at the point of linking. - self.assertEqual(a.value, b.count) - - # Change one of the values to make sure they stay in sync. - a.value = 5 - self.assertEqual(a.value, b.count) - b.count = 4 - self.assertEqual(a.value, b.count) - - def test_unlink(self): - """Verify two linked traitlets can be unlinked.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - a = A(value=9) - b = A(value=8) - - # Connect the two classes. - c = link((a, 'value'), (b, 'value')) - a.value = 4 - c.unlink() - - # Change one of the values to make sure they don't stay in sync. - a.value = 5 - self.assertNotEqual(a.value, b.value) - - def test_callbacks(self): - """Verify two linked traitlets have their callbacks called once.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - class B(HasTraits): - count = Int() - a = A(value=9) - b = B(count=8) - - # Register callbacks that count. - callback_count = [] - def a_callback(name, old, new): - callback_count.append('a') - a.on_trait_change(a_callback, 'value') - def b_callback(name, old, new): - callback_count.append('b') - b.on_trait_change(b_callback, 'count') - - # Connect the two classes. - c = link((a, 'value'), (b, 'count')) - - # Make sure b's count was set to a's value once. - self.assertEqual(''.join(callback_count), 'b') - del callback_count[:] - - # Make sure a's value was set to b's count once. - b.count = 5 - self.assertEqual(''.join(callback_count), 'ba') - del callback_count[:] - - # Make sure b's count was set to a's value once. - a.value = 4 - self.assertEqual(''.join(callback_count), 'ab') - del callback_count[:] - -class TestDirectionalLink(TestCase): - def test_connect_same(self): - """Verify two traitlets of the same type can be linked together using directional_link.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - a = A(value=9) - b = A(value=8) - - # Conenct the two classes. - c = directional_link((a, 'value'), (b, 'value')) - - # Make sure the values are the same at the point of linking. - self.assertEqual(a.value, b.value) - - # Change one the value of the source and check that it synchronizes the target. - a.value = 5 - self.assertEqual(b.value, 5) - # Change one the value of the target and check that it has no impact on the source - b.value = 6 - self.assertEqual(a.value, 5) - - def test_link_different(self): - """Verify two traitlets of different types can be linked together using link.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - class B(HasTraits): - count = Int() - a = A(value=9) - b = B(count=8) - - # Conenct the two classes. - c = directional_link((a, 'value'), (b, 'count')) - - # Make sure the values are the same at the point of linking. - self.assertEqual(a.value, b.count) - - # Change one the value of the source and check that it synchronizes the target. - a.value = 5 - self.assertEqual(b.count, 5) - # Change one the value of the target and check that it has no impact on the source - b.value = 6 - self.assertEqual(a.value, 5) - - def test_unlink(self): - """Verify two linked traitlets can be unlinked.""" - - # Create two simple classes with Int traitlets. - class A(HasTraits): - value = Int() - a = A(value=9) - b = A(value=8) - - # Connect the two classes. - c = directional_link((a, 'value'), (b, 'value')) - a.value = 4 - c.unlink() - - # Change one of the values to make sure they don't stay in sync. - a.value = 5 - self.assertNotEqual(a.value, b.value) - -class Pickleable(HasTraits): - i = Int() - j = Int() - - def _i_default(self): - return 1 - - def _i_changed(self, name, old, new): - self.j = new - -def test_pickle_hastraits(): - c = Pickleable() - for protocol in range(pickle.HIGHEST_PROTOCOL + 1): - p = pickle.dumps(c, protocol) - c2 = pickle.loads(p) - nt.assert_equal(c2.i, c.i) - nt.assert_equal(c2.j, c.j) - - c.i = 5 - for protocol in range(pickle.HIGHEST_PROTOCOL + 1): - p = pickle.dumps(c, protocol) - c2 = pickle.loads(p) - nt.assert_equal(c2.i, c.i) - nt.assert_equal(c2.j, c.j) - - -def test_hold_trait_notifications(): - changes = [] - - class Test(HasTraits): - a = Integer(0) - b = Integer(0) - - def _a_changed(self, name, old, new): - changes.append((old, new)) - - def _b_validate(self, value, trait): - if value != 0: - raise TraitError('Only 0 is a valid value') - return value - - # Test context manager and nesting - t = Test() - with t.hold_trait_notifications(): - with t.hold_trait_notifications(): - t.a = 1 - nt.assert_equal(t.a, 1) - nt.assert_equal(changes, []) - t.a = 2 - nt.assert_equal(t.a, 2) - with t.hold_trait_notifications(): - t.a = 3 - nt.assert_equal(t.a, 3) - nt.assert_equal(changes, []) - t.a = 4 - nt.assert_equal(t.a, 4) - nt.assert_equal(changes, []) - t.a = 4 - nt.assert_equal(t.a, 4) - nt.assert_equal(changes, []) - - nt.assert_equal(changes, [(0, 4)]) - # Test roll-back - try: - with t.hold_trait_notifications(): - t.b = 1 # raises a Trait error - except: - pass - nt.assert_equal(t.b, 0) - - -class RollBack(HasTraits): - bar = Int() - def _bar_validate(self, value, trait): - if value: - raise TraitError('foobar') - return value - - -class TestRollback(TestCase): - - def test_roll_back(self): - - def assign_rollback(): - RollBack(bar=1) - - self.assertRaises(TraitError, assign_rollback) - - -class OrderTraits(HasTraits): - notified = Dict() - - a = Unicode() - b = Unicode() - c = Unicode() - d = Unicode() - e = Unicode() - f = Unicode() - g = Unicode() - h = Unicode() - i = Unicode() - j = Unicode() - k = Unicode() - l = Unicode() - - def _notify(self, name, old, new): - """check the value of all traits when each trait change is triggered - - This verifies that the values are not sensitive - to dict ordering when loaded from kwargs - """ - # check the value of the other traits - # when a given trait change notification fires - self.notified[name] = { - c: getattr(self, c) for c in 'abcdefghijkl' - } - - def __init__(self, **kwargs): - self.on_trait_change(self._notify) - super(OrderTraits, self).__init__(**kwargs) - -def test_notification_order(): - d = {c:c for c in 'abcdefghijkl'} - obj = OrderTraits() - nt.assert_equal(obj.notified, {}) - obj = OrderTraits(**d) - notifications = { - c: d for c in 'abcdefghijkl' - } - nt.assert_equal(obj.notified, notifications) - - - -### -# Traits for Forward Declaration Tests -### -class ForwardDeclaredInstanceTrait(HasTraits): - - value = ForwardDeclaredInstance('ForwardDeclaredBar', allow_none=True) - -class ForwardDeclaredTypeTrait(HasTraits): - - value = ForwardDeclaredType('ForwardDeclaredBar', allow_none=True) - -class ForwardDeclaredInstanceListTrait(HasTraits): - - value = List(ForwardDeclaredInstance('ForwardDeclaredBar')) - -class ForwardDeclaredTypeListTrait(HasTraits): - - value = List(ForwardDeclaredType('ForwardDeclaredBar')) -### -# End Traits for Forward Declaration Tests -### - -### -# Classes for Forward Declaration Tests -### -class ForwardDeclaredBar(object): - pass - -class ForwardDeclaredBarSub(ForwardDeclaredBar): - pass -### -# End Classes for Forward Declaration Tests -### - -### -# Forward Declaration Tests -### -class TestForwardDeclaredInstanceTrait(TraitTestBase): - - obj = ForwardDeclaredInstanceTrait() - _default_value = None - _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()] - _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub] - -class TestForwardDeclaredTypeTrait(TraitTestBase): - - obj = ForwardDeclaredTypeTrait() - _default_value = None - _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub] - _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()] - -class TestForwardDeclaredInstanceList(TraitTestBase): - - obj = ForwardDeclaredInstanceListTrait() - - def test_klass(self): - """Test that the instance klass is properly assigned.""" - self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar) - - _default_value = [] - _good_values = [ - [ForwardDeclaredBar(), ForwardDeclaredBarSub()], - [], - ] - _bad_values = [ - ForwardDeclaredBar(), - [ForwardDeclaredBar(), 3, None], - '1', - # Note that this is the type, not an instance. - [ForwardDeclaredBar], - [None], - None, - ] - -class TestForwardDeclaredTypeList(TraitTestBase): - - obj = ForwardDeclaredTypeListTrait() - - def test_klass(self): - """Test that the instance klass is properly assigned.""" - self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar) - - _default_value = [] - _good_values = [ - [ForwardDeclaredBar, ForwardDeclaredBarSub], - [], - ] - _bad_values = [ - ForwardDeclaredBar, - [ForwardDeclaredBar, 3], - '1', - # Note that this is an instance, not the type. - [ForwardDeclaredBar()], - [None], - None, - ] -### -# End Forward Declaration Tests -### - -class TestDynamicTraits(TestCase): - - def setUp(self): - self._notify1 = [] - - def notify1(self, name, old, new): - self._notify1.append((name, old, new)) - - def test_notify_all(self): - - class A(HasTraits): - pass - - a = A() - self.assertTrue(not hasattr(a, 'x')) - self.assertTrue(not hasattr(a, 'y')) - - # Dynamically add trait x. - a.add_trait('x', Int()) - self.assertTrue(hasattr(a, 'x')) - self.assertTrue(isinstance(a, (A, ))) - - # Dynamically add trait y. - a.add_trait('y', Float()) - self.assertTrue(hasattr(a, 'y')) - self.assertTrue(isinstance(a, (A, ))) - self.assertEqual(a.__class__.__name__, A.__name__) - - # Create a new instance and verify that x and y - # aren't defined. - b = A() - self.assertTrue(not hasattr(b, 'x')) - self.assertTrue(not hasattr(b, 'y')) - - # Verify that notification works like normal. - a.on_trait_change(self.notify1) - a.x = 0 - self.assertEqual(len(self._notify1), 0) - a.y = 0.0 - self.assertEqual(len(self._notify1), 0) - a.x = 10 - self.assertTrue(('x', 0, 10) in self._notify1) - a.y = 10.0 - self.assertTrue(('y', 0.0, 10.0) in self._notify1) - self.assertRaises(TraitError, setattr, a, 'x', 'bad string') - self.assertRaises(TraitError, setattr, a, 'y', 'bad string') - self._notify1 = [] - a.on_trait_change(self.notify1, remove=True) - a.x = 20 - a.y = 20.0 - self.assertEqual(len(self._notify1), 0) diff --git a/traitlets/tests/utils.py b/traitlets/tests/utils.py deleted file mode 100644 index 34bc062..0000000 --- a/traitlets/tests/utils.py +++ /dev/null @@ -1,40 +0,0 @@ -import sys -import nose.tools as nt - -from subprocess import Popen, PIPE - -def get_output_error_code(cmd): - """Get stdout, stderr, and exit code from running a command""" - p = Popen(cmd, stdout=PIPE, stderr=PIPE) - out, err = p.communicate() - out = out.decode('utf8', 'replace') - err = err.decode('utf8', 'replace') - return out, err, p.returncode - - -def check_help_output(pkg, subcommand=None): - """test that `python -m PKG [subcommand] -h` works""" - cmd = [sys.executable, '-m', pkg] - if subcommand: - cmd.extend(subcommand) - cmd.append('-h') - out, err, rc = get_output_error_code(cmd) - nt.assert_equal(rc, 0, err) - nt.assert_not_in("Traceback", err) - nt.assert_in("Options", out) - nt.assert_in("--help-all", out) - return out, err - - -def check_help_all_output(pkg, subcommand=None): - """test that `python -m PKG --help-all` works""" - cmd = [sys.executable, '-m', pkg] - if subcommand: - cmd.extend(subcommand) - cmd.append('--help-all') - out, err, rc = get_output_error_code(cmd) - nt.assert_equal(rc, 0, err) - nt.assert_not_in("Traceback", err) - nt.assert_in("Options", out) - nt.assert_in("Class parameters", out) - return out, err diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py deleted file mode 100644 index 44eb108..0000000 --- a/traitlets/traitlets.py +++ /dev/null @@ -1,1825 +0,0 @@ -# encoding: utf-8 -""" -A lightweight Traits like module. - -This is designed to provide a lightweight, simple, pure Python version of -many of the capabilities of enthought.traits. This includes: - -* Validation -* Type specification with defaults -* Static and dynamic notification -* Basic predefined types -* An API that is similar to enthought.traits - -We don't support: - -* Delegation -* Automatic GUI generation -* A full set of trait types. Most importantly, we don't provide container - traits (list, dict, tuple) that can trigger notifications if their - contents change. -* API compatibility with enthought.traits - -There are also some important difference in our design: - -* enthought.traits does not validate default values. We do. - -We choose to create this module because we need these capabilities, but -we need them to be pure Python so they work in all Python implementations, -including Jython and IronPython. - -Inheritance diagram: - -.. inheritance-diagram:: IPython.utils.traitlets - :parts: 3 -""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. -# -# Adapted from enthought.traits, Copyright (c) Enthought, Inc., -# also under the terms of the Modified BSD License. - -import contextlib -import inspect -import re -import sys -import types -from types import FunctionType -try: - from types import ClassType, InstanceType - ClassTypes = (ClassType, type) -except: - ClassTypes = (type,) -from warnings import warn - -from IPython.utils import py3compat -from .getargspec import getargspec -from IPython.utils.importstring import import_item -from IPython.utils.py3compat import iteritems, string_types - -from .sentinel import Sentinel -SequenceTypes = (list, tuple, set, frozenset) - -#----------------------------------------------------------------------------- -# Basic classes -#----------------------------------------------------------------------------- - - -NoDefaultSpecified = Sentinel('NoDefaultSpecified', __name__, -''' -Used in Traitlets to specify that no defaults are set in kwargs -''' -) - - -class Undefined ( object ): pass -Undefined = Undefined() - -class TraitError(Exception): - pass - -#----------------------------------------------------------------------------- -# Utilities -#----------------------------------------------------------------------------- - - -def class_of ( object ): - """ Returns a string containing the class name of an object with the - correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', - 'a PlotValue'). - """ - if isinstance( object, py3compat.string_types ): - return add_article( object ) - - return add_article( object.__class__.__name__ ) - - -def add_article ( name ): - """ Returns a string containing the correct indefinite article ('a' or 'an') - prefixed to the specified string. - """ - if name[:1].lower() in 'aeiou': - return 'an ' + name - - return 'a ' + name - - -def repr_type(obj): - """ Return a string representation of a value and its type for readable - error messages. - """ - the_type = type(obj) - if (not py3compat.PY3) and the_type is InstanceType: - # Old-style class. - the_type = obj.__class__ - msg = '%r %r' % (obj, the_type) - return msg - - -def is_trait(t): - """ Returns whether the given value is an instance or subclass of TraitType. - """ - return (isinstance(t, TraitType) or - (isinstance(t, type) and issubclass(t, TraitType))) - - -def parse_notifier_name(name): - """Convert the name argument to a list of names. - - Examples - -------- - - >>> parse_notifier_name('a') - ['a'] - >>> parse_notifier_name(['a','b']) - ['a', 'b'] - >>> parse_notifier_name(None) - ['anytrait'] - """ - if isinstance(name, string_types): - return [name] - elif name is None: - return ['anytrait'] - elif isinstance(name, (list, tuple)): - for n in name: - assert isinstance(n, string_types), "names must be strings" - return name - - -class _SimpleTest: - def __init__ ( self, value ): self.value = value - def __call__ ( self, test ): - return test == self.value - def __repr__(self): - return ">> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value')) - >>> obj1.value = 5 # updates other objects as well - """ - updating = False - def __init__(self, *args): - if len(args) < 2: - raise TypeError('At least two traitlets must be provided.') - _validate_link(*args) - - self.objects = {} - - initial = getattr(args[0][0], args[0][1]) - for obj, attr in args: - setattr(obj, attr, initial) - - callback = self._make_closure(obj, attr) - obj.on_trait_change(callback, attr) - self.objects[(obj, attr)] = callback - - @contextlib.contextmanager - def _busy_updating(self): - self.updating = True - try: - yield - finally: - self.updating = False - - def _make_closure(self, sending_obj, sending_attr): - def update(name, old, new): - self._update(sending_obj, sending_attr, new) - return update - - def _update(self, sending_obj, sending_attr, new): - if self.updating: - return - with self._busy_updating(): - for obj, attr in self.objects.keys(): - setattr(obj, attr, new) - - def unlink(self): - for key, callback in self.objects.items(): - (obj, attr) = key - obj.on_trait_change(callback, attr, remove=True) - -class directional_link(object): - """Link the trait of a source object with traits of target objects. - - Parameters - ---------- - source : pair of object, name - targets : pairs of objects/attributes - - Examples - -------- - - >>> c = directional_link((src, 'value'), (tgt1, 'value'), (tgt2, 'value')) - >>> src.value = 5 # updates target objects - >>> tgt1.value = 6 # does not update other objects - """ - updating = False - - def __init__(self, source, *targets): - if len(targets) < 1: - raise TypeError('At least two traitlets must be provided.') - _validate_link(source, *targets) - self.source = source - self.targets = targets - - # Update current value - src_attr_value = getattr(source[0], source[1]) - for obj, attr in targets: - setattr(obj, attr, src_attr_value) - - # Wire - self.source[0].on_trait_change(self._update, self.source[1]) - - @contextlib.contextmanager - def _busy_updating(self): - self.updating = True - try: - yield - finally: - self.updating = False - - def _update(self, name, old, new): - if self.updating: - return - with self._busy_updating(): - for obj, attr in self.targets: - setattr(obj, attr, new) - - def unlink(self): - self.source[0].on_trait_change(self._update, self.source[1], remove=True) - self.source = None - self.targets = [] - -dlink = directional_link - - -#----------------------------------------------------------------------------- -# Base TraitType for all traits -#----------------------------------------------------------------------------- - - -class TraitType(object): - """A base class for all trait descriptors. - - Notes - ----- - Our implementation of traits is based on Python's descriptor - prototol. This class is the base class for all such descriptors. The - only magic we use is a custom metaclass for the main :class:`HasTraits` - class that does the following: - - 1. Sets the :attr:`name` attribute of every :class:`TraitType` - instance in the class dict to the name of the attribute. - 2. Sets the :attr:`this_class` attribute of every :class:`TraitType` - instance in the class dict to the *class* that declared the trait. - This is used by the :class:`This` trait to allow subclasses to - accept superclasses for :class:`This` values. - """ - - metadata = {} - default_value = Undefined - allow_none = False - info_text = 'any value' - - def __init__(self, default_value=NoDefaultSpecified, allow_none=None, **metadata): - """Create a TraitType. - """ - if default_value is not NoDefaultSpecified: - self.default_value = default_value - if allow_none is not None: - self.allow_none = allow_none - - if 'default' in metadata: - # Warn the user that they probably meant default_value. - warn( - "Parameter 'default' passed to TraitType. " - "Did you mean 'default_value'?" - ) - - if len(metadata) > 0: - if len(self.metadata) > 0: - self._metadata = self.metadata.copy() - self._metadata.update(metadata) - else: - self._metadata = metadata - else: - self._metadata = self.metadata - - self.init() - - def init(self): - pass - - def get_default_value(self): - """Create a new instance of the default value.""" - return self.default_value - - def instance_init(self): - """Part of the initialization which may depends on the underlying - HasTraits instance. - - It is typically overloaded for specific trait types. - - This method is called by :meth:`HasTraits.__new__` and in the - :meth:`TraitType.instance_init` method of trait types holding - other trait types. - """ - pass - - def init_default_value(self, obj): - """Instantiate the default value for the trait type. - - This method is called by :meth:`TraitType.set_default_value` in the - case a default value is provided at construction time or later when - accessing the trait value for the first time in - :meth:`HasTraits.__get__`. - """ - value = self.get_default_value() - value = self._validate(obj, value) - obj._trait_values[self.name] = value - return value - - def set_default_value(self, obj): - """Set the default value on a per instance basis. - - This method is called by :meth:`HasTraits.__new__` to instantiate and - validate the default value. The creation and validation of - default values must be delayed until the parent :class:`HasTraits` - class has been instantiated. - Parameters - ---------- - obj : :class:`HasTraits` instance - The parent :class:`HasTraits` instance that has just been - created. - """ - # Check for a deferred initializer defined in the same class as the - # trait declaration or above. - mro = type(obj).mro() - meth_name = '_%s_default' % self.name - for cls in mro[:mro.index(self.this_class)+1]: - if meth_name in cls.__dict__: - break - else: - # We didn't find one. Do static initialization. - self.init_default_value(obj) - return - # Complete the dynamic initialization. - obj._trait_dyn_inits[self.name] = meth_name - - def __get__(self, obj, cls=None): - """Get the value of the trait by self.name for the instance. - - Default values are instantiated when :meth:`HasTraits.__new__` - is called. Thus by the time this method gets called either the - default value or a user defined value (they called :meth:`__set__`) - is in the :class:`HasTraits` instance. - """ - if obj is None: - return self - else: - try: - value = obj._trait_values[self.name] - except KeyError: - # Check for a dynamic initializer. - if self.name in obj._trait_dyn_inits: - method = getattr(obj, obj._trait_dyn_inits[self.name]) - value = method() - # FIXME: Do we really validate here? - value = self._validate(obj, value) - obj._trait_values[self.name] = value - return value - else: - return self.init_default_value(obj) - except Exception: - # HasTraits should call set_default_value to populate - # this. So this should never be reached. - raise TraitError('Unexpected error in TraitType: ' - 'default value not set properly') - else: - return value - - def __set__(self, obj, value): - new_value = self._validate(obj, value) - try: - old_value = obj._trait_values[self.name] - except KeyError: - old_value = Undefined - - obj._trait_values[self.name] = new_value - try: - silent = bool(old_value == new_value) - except: - # if there is an error in comparing, default to notify - silent = False - if silent is not True: - # we explicitly compare silent to True just in case the equality - # comparison above returns something other than True/False - obj._notify_trait(self.name, old_value, new_value) - - def _validate(self, obj, value): - if value is None and self.allow_none: - return value - if hasattr(self, 'validate'): - value = self.validate(obj, value) - if obj._cross_validation_lock is False: - value = self._cross_validate(obj, value) - return value - - def _cross_validate(self, obj, value): - if hasattr(obj, '_%s_validate' % self.name): - cross_validate = getattr(obj, '_%s_validate' % self.name) - value = cross_validate(value, self) - return value - - def __or__(self, other): - if isinstance(other, Union): - return Union([self] + other.trait_types) - else: - return Union([self, other]) - - def info(self): - return self.info_text - - def error(self, obj, value): - if obj is not None: - e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ - % (self.name, class_of(obj), - self.info(), repr_type(value)) - else: - e = "The '%s' trait must be %s, but a value of %r was specified." \ - % (self.name, self.info(), repr_type(value)) - raise TraitError(e) - - def get_metadata(self, key, default=None): - return getattr(self, '_metadata', {}).get(key, default) - - def set_metadata(self, key, value): - getattr(self, '_metadata', {})[key] = value - - -#----------------------------------------------------------------------------- -# The HasTraits implementation -#----------------------------------------------------------------------------- - - -class MetaHasTraits(type): - """A metaclass for HasTraits. - - This metaclass makes sure that any TraitType class attributes are - instantiated and sets their name attribute. - """ - - def __new__(mcls, name, bases, classdict): - """Create the HasTraits class. - - This instantiates all TraitTypes in the class dict and sets their - :attr:`name` attribute. - """ - # print "MetaHasTraitlets (mcls, name): ", mcls, name - # print "MetaHasTraitlets (bases): ", bases - # print "MetaHasTraitlets (classdict): ", classdict - for k,v in iteritems(classdict): - if isinstance(v, TraitType): - v.name = k - elif inspect.isclass(v): - if issubclass(v, TraitType): - vinst = v() - vinst.name = k - classdict[k] = vinst - return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict) - - def __init__(cls, name, bases, classdict): - """Finish initializing the HasTraits class. - - This sets the :attr:`this_class` attribute of each TraitType in the - class dict to the newly created class ``cls``. - """ - for k, v in iteritems(classdict): - if isinstance(v, TraitType): - v.this_class = cls - super(MetaHasTraits, cls).__init__(name, bases, classdict) - - -class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)): - - def __new__(cls, *args, **kw): - # This is needed because object.__new__ only accepts - # the cls argument. - new_meth = super(HasTraits, cls).__new__ - if new_meth is object.__new__: - inst = new_meth(cls) - else: - inst = new_meth(cls, **kw) - inst._trait_values = {} - inst._trait_notifiers = {} - inst._trait_dyn_inits = {} - inst._cross_validation_lock = True - # Here we tell all the TraitType instances to set their default - # values on the instance. - for key in dir(cls): - # Some descriptors raise AttributeError like zope.interface's - # __provides__ attributes even though they exist. This causes - # AttributeErrors even though they are listed in dir(cls). - try: - value = getattr(cls, key) - except AttributeError: - pass - else: - if isinstance(value, TraitType): - value.instance_init() - if key not in kw: - value.set_default_value(inst) - inst._cross_validation_lock = False - return inst - - def __init__(self, *args, **kw): - # Allow trait values to be set using keyword arguments. - # We need to use setattr for this to trigger validation and - # notifications. - with self.hold_trait_notifications(): - for key, value in iteritems(kw): - setattr(self, key, value) - - @contextlib.contextmanager - def hold_trait_notifications(self): - """Context manager for bundling trait change notifications and cross - validation. - - Use this when doing multiple trait assignments (init, config), to avoid - race conditions in trait notifiers requesting other trait values. - All trait notifications will fire after all values have been assigned. - """ - if self._cross_validation_lock is True: - yield - return - else: - cache = {} - _notify_trait = self._notify_trait - - def merge(previous, current): - """merges notifications of the form (name, old, value)""" - if previous is None: - return current - else: - return (current[0], previous[1], current[2]) - - def hold(*a): - cache[a[0]] = merge(cache.get(a[0]), a) - - try: - self._notify_trait = hold - self._cross_validation_lock = True - yield - for name in cache: - if hasattr(self, '_%s_validate' % name): - cross_validate = getattr(self, '_%s_validate' % name) - setattr(self, name, cross_validate(getattr(self, name), self)) - except TraitError as e: - self._notify_trait = lambda *x: None - for name in cache: - if cache[name][1] is not Undefined: - setattr(self, name, cache[name][1]) - else: - self._trait_values.pop(name) - cache = {} - raise e - finally: - self._notify_trait = _notify_trait - self._cross_validation_lock = False - if isinstance(_notify_trait, types.MethodType): - # FIXME: remove when support is bumped to 3.4. - # when original method is restored, - # remove the redundant value from __dict__ - # (only used to preserve pickleability on Python < 3.4) - self.__dict__.pop('_notify_trait', None) - - # trigger delayed notifications - for v in cache.values(): - self._notify_trait(*v) - - def _notify_trait(self, name, old_value, new_value): - - # First dynamic ones - callables = [] - callables.extend(self._trait_notifiers.get(name,[])) - callables.extend(self._trait_notifiers.get('anytrait',[])) - - # Now static ones - try: - cb = getattr(self, '_%s_changed' % name) - except: - pass - else: - callables.append(cb) - - # Call them all now - for c in callables: - # Traits catches and logs errors here. I allow them to raise - if callable(c): - argspec = getargspec(c) - - nargs = len(argspec[0]) - # Bound methods have an additional 'self' argument - # I don't know how to treat unbound methods, but they - # can't really be used for callbacks. - if isinstance(c, types.MethodType): - offset = -1 - else: - offset = 0 - if nargs + offset == 0: - c() - elif nargs + offset == 1: - c(name) - elif nargs + offset == 2: - c(name, new_value) - elif nargs + offset == 3: - c(name, old_value, new_value) - else: - raise TraitError('a trait changed callback ' - 'must have 0-3 arguments.') - else: - raise TraitError('a trait changed callback ' - 'must be callable.') - - - def _add_notifiers(self, handler, name): - if name not in self._trait_notifiers: - nlist = [] - self._trait_notifiers[name] = nlist - else: - nlist = self._trait_notifiers[name] - if handler not in nlist: - nlist.append(handler) - - def _remove_notifiers(self, handler, name): - if name in self._trait_notifiers: - nlist = self._trait_notifiers[name] - try: - index = nlist.index(handler) - except ValueError: - pass - else: - del nlist[index] - - def on_trait_change(self, handler, name=None, remove=False): - """Setup a handler to be called when a trait changes. - - This is used to setup dynamic notifications of trait changes. - - Static handlers can be created by creating methods on a HasTraits - subclass with the naming convention '_[traitname]_changed'. Thus, - to create static handler for the trait 'a', create the method - _a_changed(self, name, old, new) (fewer arguments can be used, see - below). - - Parameters - ---------- - handler : callable - A callable that is called when a trait changes. Its - signature can be handler(), handler(name), handler(name, new) - or handler(name, old, new). - name : list, str, None - If None, the handler will apply to all traits. If a list - of str, handler will apply to all names in the list. If a - str, the handler will apply just to that name. - remove : bool - If False (the default), then install the handler. If True - then unintall it. - """ - if remove: - names = parse_notifier_name(name) - for n in names: - self._remove_notifiers(handler, n) - else: - names = parse_notifier_name(name) - for n in names: - self._add_notifiers(handler, n) - - @classmethod - def class_trait_names(cls, **metadata): - """Get a list of all the names of this class' traits. - - This method is just like the :meth:`trait_names` method, - but is unbound. - """ - return cls.class_traits(**metadata).keys() - - @classmethod - def class_traits(cls, **metadata): - """Get a `dict` of all the traits of this class. The dictionary - is keyed on the name and the values are the TraitType objects. - - This method is just like the :meth:`traits` method, but is unbound. - - The TraitTypes returned don't know anything about the values - that the various HasTrait's instances are holding. - - The metadata kwargs allow functions to be passed in which - filter traits based on metadata values. The functions should - take a single value as an argument and return a boolean. If - any function returns False, then the trait is not included in - the output. This does not allow for any simple way of - testing that a metadata name exists and has any - value because get_metadata returns None if a metadata key - doesn't exist. - """ - traits = dict([memb for memb in getmembers(cls) if - isinstance(memb[1], TraitType)]) - - if len(metadata) == 0: - return traits - - for meta_name, meta_eval in metadata.items(): - if type(meta_eval) is not FunctionType: - metadata[meta_name] = _SimpleTest(meta_eval) - - result = {} - for name, trait in traits.items(): - for meta_name, meta_eval in metadata.items(): - if not meta_eval(trait.get_metadata(meta_name)): - break - else: - result[name] = trait - - return result - - def trait_names(self, **metadata): - """Get a list of all the names of this class' traits.""" - return self.traits(**metadata).keys() - - def traits(self, **metadata): - """Get a `dict` of all the traits of this class. The dictionary - is keyed on the name and the values are the TraitType objects. - - The TraitTypes returned don't know anything about the values - that the various HasTrait's instances are holding. - - The metadata kwargs allow functions to be passed in which - filter traits based on metadata values. The functions should - take a single value as an argument and return a boolean. If - any function returns False, then the trait is not included in - the output. This does not allow for any simple way of - testing that a metadata name exists and has any - value because get_metadata returns None if a metadata key - doesn't exist. - """ - traits = dict([memb for memb in getmembers(self.__class__) if - isinstance(memb[1], TraitType)]) - - if len(metadata) == 0: - return traits - - for meta_name, meta_eval in metadata.items(): - if type(meta_eval) is not FunctionType: - metadata[meta_name] = _SimpleTest(meta_eval) - - result = {} - for name, trait in traits.items(): - for meta_name, meta_eval in metadata.items(): - if not meta_eval(trait.get_metadata(meta_name)): - break - else: - result[name] = trait - - return result - - def trait_metadata(self, traitname, key, default=None): - """Get metadata values for trait by key.""" - try: - trait = getattr(self.__class__, traitname) - except AttributeError: - raise TraitError("Class %s does not have a trait named %s" % - (self.__class__.__name__, traitname)) - else: - return trait.get_metadata(key, default) - - def add_trait(self, traitname, trait): - """Dynamically add a trait attribute to the HasTraits instance.""" - self.__class__ = type(self.__class__.__name__, (self.__class__,), - {traitname: trait}) - trait.set_default_value(self) - -#----------------------------------------------------------------------------- -# Actual TraitTypes implementations/subclasses -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# TraitTypes subclasses for handling classes and instances of classes -#----------------------------------------------------------------------------- - - -class ClassBasedTraitType(TraitType): - """ - A trait with error reporting and string -> type resolution for Type, - Instance and This. - """ - - def _resolve_string(self, string): - """ - Resolve a string supplied for a type into an actual object. - """ - return import_item(string) - - def error(self, obj, value): - kind = type(value) - if (not py3compat.PY3) and kind is InstanceType: - msg = 'class %s' % value.__class__.__name__ - else: - msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) ) - - if obj is not None: - e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ - % (self.name, class_of(obj), - self.info(), msg) - else: - e = "The '%s' trait must be %s, but a value of %r was specified." \ - % (self.name, self.info(), msg) - - raise TraitError(e) - - -class Type(ClassBasedTraitType): - """A trait whose value must be a subclass of a specified class.""" - - def __init__ (self, default_value=None, klass=None, **metadata): - """Construct a Type trait - - A Type trait specifies that its values must be subclasses of - a particular class. - - If only ``default_value`` is given, it is used for the ``klass`` as - well. - - Parameters - ---------- - default_value : class, str or None - The default value must be a subclass of klass. If an str, - the str must be a fully specified class name, like 'foo.bar.Bah'. - The string is resolved into real class, when the parent - :class:`HasTraits` class is instantiated. - klass : class, str, None - Values of this trait must be a subclass of klass. The klass - may be specified in a string like: 'foo.bar.MyClass'. - The string is resolved into real class, when the parent - :class:`HasTraits` class is instantiated. - allow_none : bool [ default True ] - Indicates whether None is allowed as an assignable value. Even if - ``False``, the default value may be ``None``. - """ - if default_value is None: - if klass is None: - klass = object - elif klass is None: - klass = default_value - - if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)): - raise TraitError("A Type trait must specify a class.") - - self.klass = klass - - super(Type, self).__init__(default_value, **metadata) - - def validate(self, obj, value): - """Validates that the value is a valid object instance.""" - if isinstance(value, py3compat.string_types): - try: - value = self._resolve_string(value) - except ImportError: - raise TraitError("The '%s' trait of %s instance must be a type, but " - "%r could not be imported" % (self.name, obj, value)) - try: - if issubclass(value, self.klass): - return value - except: - pass - - self.error(obj, value) - - def info(self): - """ Returns a description of the trait.""" - if isinstance(self.klass, py3compat.string_types): - klass = self.klass - else: - klass = self.klass.__name__ - result = 'a subclass of ' + klass - if self.allow_none: - return result + ' or None' - return result - - def instance_init(self): - self._resolve_classes() - super(Type, self).instance_init() - - def _resolve_classes(self): - if isinstance(self.klass, py3compat.string_types): - self.klass = self._resolve_string(self.klass) - if isinstance(self.default_value, py3compat.string_types): - self.default_value = self._resolve_string(self.default_value) - - def get_default_value(self): - return self.default_value - - -class DefaultValueGenerator(object): - """A class for generating new default value instances.""" - - def __init__(self, *args, **kw): - self.args = args - self.kw = kw - - def generate(self, klass): - return klass(*self.args, **self.kw) - - -class Instance(ClassBasedTraitType): - """A trait whose value must be an instance of a specified class. - - The value can also be an instance of a subclass of the specified class. - - Subclasses can declare default classes by overriding the klass attribute - """ - - klass = None - - def __init__(self, klass=None, args=None, kw=None, **metadata): - """Construct an Instance trait. - - This trait allows values that are instances of a particular - class or its subclasses. Our implementation is quite different - from that of enthough.traits as we don't allow instances to be used - for klass and we handle the ``args`` and ``kw`` arguments differently. - - Parameters - ---------- - klass : class, str - The class that forms the basis for the trait. Class names - can also be specified as strings, like 'foo.bar.Bar'. - args : tuple - Positional arguments for generating the default value. - kw : dict - Keyword arguments for generating the default value. - allow_none : bool [default True] - Indicates whether None is allowed as a value. - - Notes - ----- - If both ``args`` and ``kw`` are None, then the default value is None. - If ``args`` is a tuple and ``kw`` is a dict, then the default is - created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is - None, the None is replaced by ``()`` or ``{}``, respectively. - """ - if klass is None: - klass = self.klass - - if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)): - self.klass = klass - else: - raise TraitError('The klass attribute must be a class' - ' not: %r' % klass) - - # self.klass is a class, so handle default_value - if args is None and kw is None: - default_value = None - else: - if args is None: - # kw is not None - args = () - elif kw is None: - # args is not None - kw = {} - - if not isinstance(kw, dict): - raise TraitError("The 'kw' argument must be a dict or None.") - if not isinstance(args, tuple): - raise TraitError("The 'args' argument must be a tuple or None.") - - default_value = DefaultValueGenerator(*args, **kw) - - super(Instance, self).__init__(default_value, **metadata) - - def validate(self, obj, value): - if isinstance(value, self.klass): - return value - else: - self.error(obj, value) - - def info(self): - if isinstance(self.klass, py3compat.string_types): - klass = self.klass - else: - klass = self.klass.__name__ - result = class_of(klass) - if self.allow_none: - return result + ' or None' - - return result - - def instance_init(self): - self._resolve_classes() - super(Instance, self).instance_init() - - def _resolve_classes(self): - if isinstance(self.klass, py3compat.string_types): - self.klass = self._resolve_string(self.klass) - - def get_default_value(self): - """Instantiate a default value instance. - - This is called when the containing HasTraits classes' - :meth:`__new__` method is called to ensure that a unique instance - is created for each HasTraits instance. - """ - dv = self.default_value - if isinstance(dv, DefaultValueGenerator): - return dv.generate(self.klass) - else: - return dv - - -class ForwardDeclaredMixin(object): - """ - Mixin for forward-declared versions of Instance and Type. - """ - def _resolve_string(self, string): - """ - Find the specified class name by looking for it in the module in which - our this_class attribute was defined. - """ - modname = self.this_class.__module__ - return import_item('.'.join([modname, string])) - - -class ForwardDeclaredType(ForwardDeclaredMixin, Type): - """ - Forward-declared version of Type. - """ - pass - - -class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance): - """ - Forward-declared version of Instance. - """ - pass - - -class This(ClassBasedTraitType): - """A trait for instances of the class containing this trait. - - Because how how and when class bodies are executed, the ``This`` - trait can only have a default value of None. This, and because we - always validate default values, ``allow_none`` is *always* true. - """ - - info_text = 'an instance of the same type as the receiver or None' - - def __init__(self, **metadata): - super(This, self).__init__(None, **metadata) - - def validate(self, obj, value): - # What if value is a superclass of obj.__class__? This is - # complicated if it was the superclass that defined the This - # trait. - if isinstance(value, self.this_class) or (value is None): - return value - else: - self.error(obj, value) - - -class Union(TraitType): - """A trait type representing a Union type.""" - - def __init__(self, trait_types, **metadata): - """Construct a Union trait. - - This trait allows values that are allowed by at least one of the - specified trait types. A Union traitlet cannot have metadata on - its own, besides the metadata of the listed types. - - Parameters - ---------- - trait_types: sequence - The list of trait types of length at least 1. - - Notes - ----- - Union([Float(), Bool(), Int()]) attempts to validate the provided values - with the validation function of Float, then Bool, and finally Int. - """ - self.trait_types = trait_types - self.info_text = " or ".join([tt.info_text for tt in self.trait_types]) - self.default_value = self.trait_types[0].get_default_value() - super(Union, self).__init__(**metadata) - - def instance_init(self): - for trait_type in self.trait_types: - trait_type.name = self.name - trait_type.this_class = self.this_class - trait_type.instance_init() - super(Union, self).instance_init() - - def validate(self, obj, value): - for trait_type in self.trait_types: - try: - v = trait_type._validate(obj, value) - self._metadata = trait_type._metadata - return v - except TraitError: - continue - self.error(obj, value) - - def __or__(self, other): - if isinstance(other, Union): - return Union(self.trait_types + other.trait_types) - else: - return Union(self.trait_types + [other]) - -#----------------------------------------------------------------------------- -# Basic TraitTypes implementations/subclasses -#----------------------------------------------------------------------------- - - -class Any(TraitType): - default_value = None - info_text = 'any value' - - -class Int(TraitType): - """An int trait.""" - - default_value = 0 - info_text = 'an int' - - def validate(self, obj, value): - if isinstance(value, int): - return value - self.error(obj, value) - -class CInt(Int): - """A casting version of the int trait.""" - - def validate(self, obj, value): - try: - return int(value) - except: - self.error(obj, value) - -if py3compat.PY3: - Long, CLong = Int, CInt - Integer = Int -else: - class Long(TraitType): - """A long integer trait.""" - - default_value = 0 - info_text = 'a long' - - def validate(self, obj, value): - if isinstance(value, long): - return value - if isinstance(value, int): - return long(value) - self.error(obj, value) - - - class CLong(Long): - """A casting version of the long integer trait.""" - - def validate(self, obj, value): - try: - return long(value) - except: - self.error(obj, value) - - class Integer(TraitType): - """An integer trait. - - Longs that are unnecessary (<= sys.maxint) are cast to ints.""" - - default_value = 0 - info_text = 'an integer' - - def validate(self, obj, value): - if isinstance(value, int): - return value - if isinstance(value, long): - # downcast longs that fit in int: - # note that int(n > sys.maxint) returns a long, so - # we don't need a condition on this cast - return int(value) - if sys.platform == "cli": - from System import Int64 - if isinstance(value, Int64): - return int(value) - self.error(obj, value) - - -class Float(TraitType): - """A float trait.""" - - default_value = 0.0 - info_text = 'a float' - - def validate(self, obj, value): - if isinstance(value, float): - return value - if isinstance(value, int): - return float(value) - self.error(obj, value) - - -class CFloat(Float): - """A casting version of the float trait.""" - - def validate(self, obj, value): - try: - return float(value) - except: - self.error(obj, value) - -class Complex(TraitType): - """A trait for complex numbers.""" - - default_value = 0.0 + 0.0j - info_text = 'a complex number' - - def validate(self, obj, value): - if isinstance(value, complex): - return value - if isinstance(value, (float, int)): - return complex(value) - self.error(obj, value) - - -class CComplex(Complex): - """A casting version of the complex number trait.""" - - def validate (self, obj, value): - try: - return complex(value) - except: - self.error(obj, value) - -# We should always be explicit about whether we're using bytes or unicode, both -# for Python 3 conversion and for reliable unicode behaviour on Python 2. So -# we don't have a Str type. -class Bytes(TraitType): - """A trait for byte strings.""" - - default_value = b'' - info_text = 'a bytes object' - - def validate(self, obj, value): - if isinstance(value, bytes): - return value - self.error(obj, value) - - -class CBytes(Bytes): - """A casting version of the byte string trait.""" - - def validate(self, obj, value): - try: - return bytes(value) - except: - self.error(obj, value) - - -class Unicode(TraitType): - """A trait for unicode strings.""" - - default_value = u'' - info_text = 'a unicode string' - - def validate(self, obj, value): - if isinstance(value, py3compat.unicode_type): - return value - if isinstance(value, bytes): - try: - return value.decode('ascii', 'strict') - except UnicodeDecodeError: - msg = "Could not decode {!r} for unicode trait '{}' of {} instance." - raise TraitError(msg.format(value, self.name, class_of(obj))) - self.error(obj, value) - - -class CUnicode(Unicode): - """A casting version of the unicode trait.""" - - def validate(self, obj, value): - try: - return py3compat.unicode_type(value) - except: - self.error(obj, value) - - -class ObjectName(TraitType): - """A string holding a valid object name in this version of Python. - - This does not check that the name exists in any scope.""" - info_text = "a valid object identifier in Python" - - if py3compat.PY3: - # Python 3: - coerce_str = staticmethod(lambda _,s: s) - - else: - # Python 2: - def coerce_str(self, obj, value): - "In Python 2, coerce ascii-only unicode to str" - if isinstance(value, unicode): - try: - return str(value) - except UnicodeEncodeError: - self.error(obj, value) - return value - - def validate(self, obj, value): - value = self.coerce_str(obj, value) - - if isinstance(value, string_types) and py3compat.isidentifier(value): - return value - self.error(obj, value) - -class DottedObjectName(ObjectName): - """A string holding a valid dotted object name in Python, such as A.b3._c""" - def validate(self, obj, value): - value = self.coerce_str(obj, value) - - if isinstance(value, string_types) and py3compat.isidentifier(value, dotted=True): - return value - self.error(obj, value) - - -class Bool(TraitType): - """A boolean (True, False) trait.""" - - default_value = False - info_text = 'a boolean' - - def validate(self, obj, value): - if isinstance(value, bool): - return value - self.error(obj, value) - - -class CBool(Bool): - """A casting version of the boolean trait.""" - - def validate(self, obj, value): - try: - return bool(value) - except: - self.error(obj, value) - - -class Enum(TraitType): - """An enum that whose value must be in a given sequence.""" - - def __init__(self, values, default_value=None, **metadata): - self.values = values - super(Enum, self).__init__(default_value, **metadata) - - def validate(self, obj, value): - if value in self.values: - return value - self.error(obj, value) - - def info(self): - """ Returns a description of the trait.""" - result = 'any of ' + repr(self.values) - if self.allow_none: - return result + ' or None' - return result - -class CaselessStrEnum(Enum): - """An enum of strings that are caseless in validate.""" - - def validate(self, obj, value): - if not isinstance(value, py3compat.string_types): - self.error(obj, value) - - for v in self.values: - if v.lower() == value.lower(): - return v - self.error(obj, value) - -class Container(Instance): - """An instance of a container (list, set, etc.) - - To be subclassed by overriding klass. - """ - klass = None - _cast_types = () - _valid_defaults = SequenceTypes - _trait = None - - def __init__(self, trait=None, default_value=None, **metadata): - """Create a container trait type from a list, set, or tuple. - - The default value is created by doing ``List(default_value)``, - which creates a copy of the ``default_value``. - - ``trait`` can be specified, which restricts the type of elements - in the container to that TraitType. - - If only one arg is given and it is not a Trait, it is taken as - ``default_value``: - - ``c = List([1,2,3])`` - - Parameters - ---------- - - trait : TraitType [ optional ] - the type for restricting the contents of the Container. If unspecified, - types are not checked. - - default_value : SequenceType [ optional ] - The default value for the Trait. Must be list/tuple/set, and - will be cast to the container type. - - allow_none : bool [ default False ] - Whether to allow the value to be None - - **metadata : any - further keys for extensions to the Trait (e.g. config) - - """ - # allow List([values]): - if default_value is None and not is_trait(trait): - default_value = trait - trait = None - - if default_value is None: - args = () - elif isinstance(default_value, self._valid_defaults): - args = (default_value,) - else: - raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) - - if is_trait(trait): - self._trait = trait() if isinstance(trait, type) else trait - self._trait.name = 'element' - elif trait is not None: - raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait)) - - super(Container,self).__init__(klass=self.klass, args=args, **metadata) - - def element_error(self, obj, element, validator): - e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \ - % (self.name, class_of(obj), validator.info(), repr_type(element)) - raise TraitError(e) - - def validate(self, obj, value): - if isinstance(value, self._cast_types): - value = self.klass(value) - value = super(Container, self).validate(obj, value) - if value is None: - return value - - value = self.validate_elements(obj, value) - - return value - - def validate_elements(self, obj, value): - validated = [] - if self._trait is None or isinstance(self._trait, Any): - return value - for v in value: - try: - v = self._trait._validate(obj, v) - except TraitError: - self.element_error(obj, v, self._trait) - else: - validated.append(v) - return self.klass(validated) - - def instance_init(self): - if isinstance(self._trait, TraitType): - self._trait.this_class = self.this_class - self._trait.instance_init() - super(Container, self).instance_init() - - -class List(Container): - """An instance of a Python list.""" - klass = list - _cast_types = (tuple,) - - def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **metadata): - """Create a List trait type from a list, set, or tuple. - - The default value is created by doing ``List(default_value)``, - which creates a copy of the ``default_value``. - - ``trait`` can be specified, which restricts the type of elements - in the container to that TraitType. - - If only one arg is given and it is not a Trait, it is taken as - ``default_value``: - - ``c = List([1,2,3])`` - - Parameters - ---------- - - trait : TraitType [ optional ] - the type for restricting the contents of the Container. If unspecified, - types are not checked. - - default_value : SequenceType [ optional ] - The default value for the Trait. Must be list/tuple/set, and - will be cast to the container type. - - minlen : Int [ default 0 ] - The minimum length of the input list - - maxlen : Int [ default sys.maxsize ] - The maximum length of the input list - - allow_none : bool [ default False ] - Whether to allow the value to be None - - **metadata : any - further keys for extensions to the Trait (e.g. config) - - """ - self._minlen = minlen - self._maxlen = maxlen - super(List, self).__init__(trait=trait, default_value=default_value, - **metadata) - - def length_error(self, obj, value): - e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \ - % (self.name, class_of(obj), self._minlen, self._maxlen, value) - raise TraitError(e) - - def validate_elements(self, obj, value): - length = len(value) - if length < self._minlen or length > self._maxlen: - self.length_error(obj, value) - - return super(List, self).validate_elements(obj, value) - - def validate(self, obj, value): - value = super(List, self).validate(obj, value) - value = self.validate_elements(obj, value) - return value - - -class Set(List): - """An instance of a Python set.""" - klass = set - _cast_types = (tuple, list) - - -class Tuple(Container): - """An instance of a Python tuple.""" - klass = tuple - _cast_types = (list,) - - def __init__(self, *traits, **metadata): - """Tuple(*traits, default_value=None, **medatata) - - Create a tuple from a list, set, or tuple. - - Create a fixed-type tuple with Traits: - - ``t = Tuple(Int, Str, CStr)`` - - would be length 3, with Int,Str,CStr for each element. - - If only one arg is given and it is not a Trait, it is taken as - default_value: - - ``t = Tuple((1,2,3))`` - - Otherwise, ``default_value`` *must* be specified by keyword. - - Parameters - ---------- - - *traits : TraitTypes [ optional ] - the types for restricting the contents of the Tuple. If unspecified, - types are not checked. If specified, then each positional argument - corresponds to an element of the tuple. Tuples defined with traits - are of fixed length. - - default_value : SequenceType [ optional ] - The default value for the Tuple. Must be list/tuple/set, and - will be cast to a tuple. If `traits` are specified, the - `default_value` must conform to the shape and type they specify. - - allow_none : bool [ default False ] - Whether to allow the value to be None - - **metadata : any - further keys for extensions to the Trait (e.g. config) - - """ - default_value = metadata.pop('default_value', None) - - # allow Tuple((values,)): - if len(traits) == 1 and default_value is None and not is_trait(traits[0]): - default_value = traits[0] - traits = () - - if default_value is None: - args = () - elif isinstance(default_value, self._valid_defaults): - args = (default_value,) - else: - raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) - - self._traits = [] - for trait in traits: - t = trait() if isinstance(trait, type) else trait - t.name = 'element' - self._traits.append(t) - - if self._traits and default_value is None: - # don't allow default to be an empty container if length is specified - args = None - super(Container,self).__init__(klass=self.klass, args=args, **metadata) - - def validate_elements(self, obj, value): - if not self._traits: - # nothing to validate - return value - if len(value) != len(self._traits): - e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \ - % (self.name, class_of(obj), len(self._traits), repr_type(value)) - raise TraitError(e) - - validated = [] - for t, v in zip(self._traits, value): - try: - v = t._validate(obj, v) - except TraitError: - self.element_error(obj, v, t) - else: - validated.append(v) - return tuple(validated) - - def instance_init(self): - for trait in self._traits: - if isinstance(trait, TraitType): - trait.this_class = self.this_class - trait.instance_init() - super(Container, self).instance_init() - - -class Dict(Instance): - """An instance of a Python dict.""" - _trait = None - - def __init__(self, trait=None, default_value=NoDefaultSpecified, **metadata): - """Create a dict trait type from a dict. - - The default value is created by doing ``dict(default_value)``, - which creates a copy of the ``default_value``. - - trait : TraitType [ optional ] - the type for restricting the contents of the Container. If unspecified, - types are not checked. - - default_value : SequenceType [ optional ] - The default value for the Dict. Must be dict, tuple, or None, and - will be cast to a dict if not None. If `trait` is specified, the - `default_value` must conform to the constraints it specifies. - - allow_none : bool [ default False ] - Whether to allow the value to be None - - """ - if default_value is NoDefaultSpecified and trait is not None: - if not is_trait(trait): - default_value = trait - trait = None - if default_value is NoDefaultSpecified: - default_value = {} - if default_value is None: - args = None - elif isinstance(default_value, dict): - args = (default_value,) - elif isinstance(default_value, SequenceTypes): - args = (default_value,) - else: - raise TypeError('default value of Dict was %s' % default_value) - - if is_trait(trait): - self._trait = trait() if isinstance(trait, type) else trait - self._trait.name = 'element' - elif trait is not None: - raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait)) - - super(Dict,self).__init__(klass=dict, args=args, **metadata) - - def element_error(self, obj, element, validator): - e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \ - % (self.name, class_of(obj), validator.info(), repr_type(element)) - raise TraitError(e) - - def validate(self, obj, value): - value = super(Dict, self).validate(obj, value) - if value is None: - return value - value = self.validate_elements(obj, value) - return value - - def validate_elements(self, obj, value): - if self._trait is None or isinstance(self._trait, Any): - return value - validated = {} - for key in value: - v = value[key] - try: - v = self._trait._validate(obj, v) - except TraitError: - self.element_error(obj, v, self._trait) - else: - validated[key] = v - return self.klass(validated) - - def instance_init(self): - if isinstance(self._trait, TraitType): - self._trait.this_class = self.this_class - self._trait.instance_init() - super(Dict, self).instance_init() - - -class TCPAddress(TraitType): - """A trait for an (ip, port) tuple. - - This allows for both IPv4 IP addresses as well as hostnames. - """ - - default_value = ('127.0.0.1', 0) - info_text = 'an (ip, port) tuple' - - def validate(self, obj, value): - if isinstance(value, tuple): - if len(value) == 2: - if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int): - port = value[1] - if port >= 0 and port <= 65535: - return value - self.error(obj, value) - -class CRegExp(TraitType): - """A casting compiled regular expression trait. - - Accepts both strings and compiled regular expressions. The resulting - attribute will be a compiled regular expression.""" - - info_text = 'a regular expression' - - def validate(self, obj, value): - try: - return re.compile(value) - except: - self.error(obj, value)