Пример #1
0
class InputTransformer(with_metaclass(abc.ABCMeta, object)):
    """Abstract base class for line-based input transformers."""
    @abc.abstractmethod
    def push(self, line):
        """Send a line of input to the transformer, returning the transformed
        input or None if the transformer is waiting for more input.
        
        Must be overridden by subclasses.

        Implementations may raise ``SyntaxError`` if the input is invalid. No
        other exceptions may be raised.
        """
        pass

    @abc.abstractmethod
    def reset(self):
        """Return, transformed any lines that the transformer has accumulated,
        and reset its internal state.
        
        Must be overridden by subclasses.
        """
        pass

    @classmethod
    def wrap(cls, func):
        """Can be used by subclasses as a decorator, to return a factory that
        will allow instantiation with the decorated object.
        """
        @functools.wraps(func)
        def transformer_factory(**kwargs):
            return cls(func, **kwargs)

        return transformer_factory
Пример #2
0
class FormatterABC(with_metaclass(abc.ABCMeta, object)):
    """ Abstract base class for Formatters.

    A formatter is a callable class that is responsible for computing the
    raw format data for a particular format type (MIME type). For example,
    an HTML formatter would have a format type of `text/html` and would return
    the HTML representation of the object when called.
    """

    # The format type of the data returned, usually a MIME type.
    format_type = 'text/plain'

    # Is the formatter enabled...
    enabled = True

    @abc.abstractmethod
    def __call__(self, obj):
        """Return a JSON'able representation of the object.

        If the object cannot be formatted by this formatter, then return None
        """
        try:
            return repr(obj)
        except Exception:
            return None
Пример #3
0
class SocketABC(with_metaclass(abc.ABCMeta, object)):
    @abc.abstractmethod
    def recv_multipart(self, flags=0, copy=True, track=False):
        raise NotImplementedError

    @abc.abstractmethod
    def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
        raise NotImplementedError
Пример #4
0
class KernelClientABC(with_metaclass(abc.ABCMeta, object)):
    """KernelManager ABC.

    The docstrings for this class can be found in the base implementation:

    `IPython.kernel.client.KernelClient`
    """
    @abc.abstractproperty
    def kernel(self):
        pass

    @abc.abstractproperty
    def shell_channel_class(self):
        pass

    @abc.abstractproperty
    def iopub_channel_class(self):
        pass

    @abc.abstractproperty
    def hb_channel_class(self):
        pass

    @abc.abstractproperty
    def stdin_channel_class(self):
        pass

    #--------------------------------------------------------------------------
    # Channel management methods
    #--------------------------------------------------------------------------

    @abc.abstractmethod
    def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
        pass

    @abc.abstractmethod
    def stop_channels(self):
        pass

    @abc.abstractproperty
    def channels_running(self):
        pass

    @abc.abstractproperty
    def shell_channel(self):
        pass

    @abc.abstractproperty
    def iopub_channel(self):
        pass

    @abc.abstractproperty
    def stdin_channel(self):
        pass

    @abc.abstractproperty
    def hb_channel(self):
        pass
Пример #5
0
class ChannelABC(with_metaclass(abc.ABCMeta, object)):
    """A base class for all channel ABCs."""
    @abc.abstractmethod
    def start(self):
        pass

    @abc.abstractmethod
    def stop(self):
        pass

    @abc.abstractmethod
    def is_alive(self):
        pass
Пример #6
0
class KernelManagerABC(with_metaclass(abc.ABCMeta, object)):
    """KernelManager ABC.

    The docstrings for this class can be found in the base implementation:

    `IPython.kernel.kernelmanager.KernelManager`
    """

    @abc.abstractproperty
    def kernel(self):
        pass

    #--------------------------------------------------------------------------
    # Kernel management
    #--------------------------------------------------------------------------

    @abc.abstractmethod
    def start_kernel(self, **kw):
        pass

    @abc.abstractmethod
    def shutdown_kernel(self, now=False, restart=False):
        pass

    @abc.abstractmethod
    def restart_kernel(self, now=False, **kw):
        pass

    @abc.abstractproperty
    def has_kernel(self):
        pass

    @abc.abstractmethod
    def interrupt_kernel(self):
        pass

    @abc.abstractmethod
    def signal_kernel(self, signum):
        pass

    @abc.abstractmethod
    def is_alive(self):
        pass
Пример #7
0
class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
    def __new__(cls, *args, **kw):
        # This is needed because in Python 2.6 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 = {}
        # 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(inst)

        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.
        for key, value in iteritems(kw):
            setattr(self, key, value)

    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 = inspect.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 classes 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 list of all the traits of this class.

        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.

        This follows the same algorithm as traits does and does not allow
        for any simple way of specifying merely that a metadata name
        exists, but has any value.  This is 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 classes traits."""
        return self.traits(**metadata).keys()

    def traits(self, **metadata):
        """Get a list of all the traits of this class.

        The TraitTypes returned don't know anything about the values
        that the various HasTrait's instances are holding.

        This follows the same algorithm as traits does and does not allow
        for any simple way of specifying merely that a metadata name
        exists, but has any value.  This is 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):
        """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)
Пример #8
0
class KernelManagerABC(with_metaclass(abc.ABCMeta, object)):
    """KernelManager ABC.

    The docstrings for this class can be found in the base implementation:

    `IPython.kernel.kernelmanager.KernelManager`
    """
    @abc.abstractproperty
    def kernel(self):
        pass

    @abc.abstractproperty
    def shell_channel_class(self):
        pass

    @abc.abstractproperty
    def iopub_channel_class(self):
        pass

    @abc.abstractproperty
    def hb_channel_class(self):
        pass

    @abc.abstractproperty
    def stdin_channel_class(self):
        pass

    #--------------------------------------------------------------------------
    # Channel management methods
    #--------------------------------------------------------------------------

    @abc.abstractmethod
    def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
        pass

    @abc.abstractmethod
    def stop_channels(self):
        pass

    @abc.abstractproperty
    def channels_running(self):
        pass

    @abc.abstractproperty
    def shell_channel(self):
        pass

    @abc.abstractproperty
    def iopub_channel(self):
        pass

    @abc.abstractproperty
    def stdin_channel(self):
        pass

    @abc.abstractproperty
    def hb_channel(self):
        pass

    #--------------------------------------------------------------------------
    # Kernel management
    #--------------------------------------------------------------------------

    @abc.abstractmethod
    def start_kernel(self, **kw):
        pass

    @abc.abstractmethod
    def shutdown_kernel(self, now=False, restart=False):
        pass

    @abc.abstractmethod
    def restart_kernel(self, now=False, **kw):
        pass

    @abc.abstractproperty
    def has_kernel(self):
        pass

    @abc.abstractmethod
    def interrupt_kernel(self):
        pass

    @abc.abstractmethod
    def signal_kernel(self, signum):
        pass

    @abc.abstractmethod
    def is_alive(self):
        pass
Пример #9
0
class BaseDocument(with_metaclass(Meta, traitlets.HasTraits)):

    _id = ObjectIdTrait()

    db_default = True
    _class_tag = False


    @property
    def id(self):
        return self._id
    @id.setter
    def id(self, value):
        self._id = value

    def __init__(self, *args, **kwargs):
        super(BaseDocument,self).__init__(*args, **kwargs)
        self.check_instance()

    def check_instance(self, _id=None):
        errstr = "Trying to instantiate two objects with the same id"
        if _id is None:
            _id = self._id
        if _id in self.__class__._idrefs:
            raise MongoTraitsError(errstr)
        if _id is not None:
            self.__class__._idrefs[_id] = self

    @classmethod
    def resolve_instance(cls, kwargsdict, allow_update = False):
        errstr = ("Local and database objects are inconsistent and"
        " allow_update is set to false.")
        if cls._class_tag:
            kwargsdict.pop('_cls')
        kwargsdict = cls.to_classdict(kwargsdict,allow_update)
        if '_id' in kwargsdict:
            uid =  kwargsdict['_id']
            if uid in cls._idrefs:
                ins = cls._idrefs[uid]
                for key, value in kwargsdict.items():
                    if value != getattr(ins, key):
                        if allow_update:
                            setattr(ins,key, value)
                        else:
                            raise MongoTraitsError(errstr)
                return ins
        ins = cls(**kwargsdict)
        return ins

    @classmethod
    def to_classdict(cls,kwargsdict, allow_update = False ):
        result = {}
        if cls.db_default:
            traits = cls.class_traits(db=lambda x: x is not False)
        else:
            traits = cls.class_traits(db=True)
        instance_traits = {key:value for (key,value) in traits.items()
            if isinstance(value, traitlets.ClassBasedTraitType) }

        container_traits = {key:value for (key,value) in traits.items()
            if isinstance(value, traitlets.Container) }

        for (key, value) in kwargsdict.items():
            if key in container_traits:
                result[key] = cls.to_container(value,container_traits[key],
                                allow_update)
            elif key in instance_traits:
                result[key] = cls.to_instance(value,instance_traits[key],
                                 allow_update)

            else:
                result[key] = value
        return result

    @classmethod
    def to_instance(cls, value ,trait ,allow_update = False):
        klass = trait.klass
        if hasattr(trait, 'dereference'):
            return trait.dereference(value)
        elif value is None:
            return value
        elif hasattr(klass,'resolve_instance'):
            return klass.resolve_instance(value,
                                          allow_update=allow_update)
        elif issubclass(klass, SAME_TYPES):
            return value
        else:
            return pickle.loads(value)

    @classmethod
    def to_container(cls, value, trait, allow_update):
        _trait =  trait._trait
        if _trait is not None and hasattr(_trait, 'klass'):
            l = []
            for item in value:
                l += [cls.to_instance(item,_trait, allow_update)]
            return trait.klass(l)
        else:
           return trait.klass(value)

    @property
    def savedict(self):
        savedict={}
        if self.db_default:
            traits = self.traits(db = lambda x: x is not False).values()
        else:
            traits = self.traits(db=lambda x: x).values()

        for trait in traits:
            name = trait.name
            value = self.encode_item(trait, self._trait_values[name])
            savedict[name] = value
        if self._class_tag:
            savedict['_cls'] = self.__class__.__name__
        return savedict

    @staticmethod
    def encode_item(trait, value):
        if value is None:
            return value
        elif hasattr(trait, 'reference'):
            value = trait.reference(value)
        elif 'savedict' in dir(value):
            value = value.savedict
        elif isinstance(trait, traitlets.Container):
            value = [Document.encode_item(trait._trait,elem) for elem in value]
        elif not isinstance(value, SAME_TYPES):
            value = binary.Binary(pickle.dumps(value))
        return value

    @property
    def references(self):
        return self._refs()

    def _refs(self, refs=None):
        if refs is None:
            refs = set()

        def add_ref(value):
            if value is not None and not value in refs:
                refs.add(value)
                value._refs(refs)

        if self.db_default:
            traits = self.traits(db = lambda x: x is not False).values()
        else:
            traits = self.traits(db=lambda x: x).values()

        for trait in traits:
            if (isinstance(trait, BaseReference) or
            (isinstance(trait, traitlets.Instance) and
            issubclass(trait.klass, BaseDocument))):
                value = self._trait_values[trait.name]
                add_ref(value)
            elif isinstance(trait, traitlets.Container):
                _trait =  trait._trait
                if (_trait is not None and
                isinstance(_trait, BaseReference)):
                    items = self._trait_values[trait.name]
                    for value in items:
                        add_ref(value)
        return refs

    @property
    def document_references(self):
        return {ref for ref in self.references if isinstance(ref,Document)}
    
    def repr_name(self):
        return self.id

    def __repr__(self):
        return "<%s: %s>"%(self.__class__.__name__, self.repr_name())

    class WidgetRepresentation(widgetrepr.WidgetRepresentation):
        
        def create_description(self):
            return "Create %s and save" % self.cls.__name__

        def new_object(self):
            obj = super(BaseDocument.WidgetRepresentation, self).new_object()
            obj.save(cascade = True)
            return obj