Exemplo n.º 1
0
class JS_On_Ready \
        (TFL.Meta.BaM (Media_Base, metaclass = TFL.Meta.M_Unique_If_Named)) :
    """A javascript code which should be executed once the document is loaded"""

    default_rank = TFL.Undef("rank")
    name = None

    def __init__(self, code, rank=default_rank, **kw):
        if isinstance(code, self.__class__):
            if rank is self.default_rank:
                rank = code.rank
            code = code.code
        elif rank is self.default_rank:
            rank = 0
        code = code.strip()
        if not code.endswith(";"):
            code += ";"
        self.code = code
        if self.rank:
            self.rank = rank
        self.pop_to_self(kw, "name")

    # end def __init__

    def __str__(self):
        return self.code
Exemplo n.º 2
0
class _Memoized_(TFL.FMW.Wrapped_FM):
    """Wrapper adding memoization to a single function or method"""

    __undef = TFL.Undef()

    def __init__(self, *args, **kw):
        self._cache = {}
        self.__super.__init__(*args, **kw)

    # end def __init__

    def __call__(self, *args):
        _cache = self._cache
        _undef = self.__undef
        result = _cache.get(args, _undef)
        if result is _undef:
            result = _cache[args] = self.fct(*args)
        return result
Exemplo n.º 3
0
def dict_let(dct, **kw):
    """Provide context with elements of dictionary `dct` temporary bound to
       values in `kw`.
    """
    store = {}
    undef = TFL.Undef()
    for k, v in pyk.iteritems(kw):
        store[k] = dct.get(k, undef)
    try:
        for k, v in pyk.iteritems(kw):
            dct[k] = v
        yield
    finally:
        for k, v in pyk.iteritems(store):
            if v is undef:
                del dct[k]
            else:
                dct[k] = v
Exemplo n.º 4
0
class Attr_Summary(TFL.Meta.Object):
    """Change summary for a single attribute of a single `pid`."""

    conflicts = False
    merges = False

    cur = ini = None
    new = old = undef = TFL.Undef("attr")

    def add(self, old, new):
        if self.old is self.undef:
            self.old = old
        self.new = new

    # end def add

    def check_conflict(self, attr, entity, ini):
        self.conflicts = False
        self.cur = cur = attr.get_raw(entity)
        self.ini = ini
        if not attr.electric:
            self.conflicts = (self.new != cur and ini != cur)
        self.merges = (self.new != ini)
        return self.conflicts

    # end def check_conflict

    def check_ini_vs_cur(self, attr, entity, ini, r_name):
        self.ini = ini
        self.cur = cur = attr.get_raw(entity)
        result = (ini != cur)
        setattr(self, r_name, result)
        return result

    # end def check_ini_vs_cur

    def __bool__(self):
        return self.old is not self.undef

    # end def __bool__

    def __repr__(self):
        return "(old = %s, new = %s)" % \
            (portable_repr (self.old), portable_repr (self.new))
Exemplo n.º 5
0
def attr_let(obj, **kw):
    """Provide context with attributes of `obj` temporary bound to
       values in `kw`.
    """
    store = {}
    undef = TFL.Undef()
    for k, v in pyk.iteritems(kw):
        store[k] = getattr(obj, k, undef)
    try:
        for k, v in pyk.iteritems(kw):
            try:
                setattr(obj, k, v)
            except AttributeError as exc:
                raise AttributeError("%s: [%s = %r]" % (exc, k, v))
        yield
    finally:
        for k, v in pyk.iteritems(store):
            if v is undef:
                delattr(obj, k)
            else:
                try:
                    setattr(obj, k, v)
                except AttributeError as exc:
                    raise AttributeError("%s: [%s = %r]" % (exc, k, v))
Exemplo n.º 6
0
#    29-Oct-2015 (CT) Improve Python 3 compatibility
#    27-Dec-2016 (CT) Add `encoding` to `as_text`
#    ««revision-date»»···
#--

from   _TFL                    import TFL
from   _PMA                    import PMA
from   _PMA                    import Lib
import _TFL._Meta.Object
import _TFL.Undef

from   _TFL.predicate          import *
from   _TFL.pyk                import pyk
from   _TFL                    import sos

_undefined = TFL.Undef ()

class Mailcap_Entry (TFL.Meta.Object) :
    """Model a single mailcap entry for a specific mime type"""

    def __init__ (self, mime_type, cap_dict) :
        self.mime_type     = mime_type
        self.cap_dict      = cap_dict
        self.copiousoutput = "copiousoutput" in cap_dict
        self.needsterminal = "needsterminal" in cap_dict
        self.test          = cap_dict.get ("test")
    # end def __init__

    def applicable (self, filename = "/dev/null", plist = []) :
        if self.test :
            test_cmd = self.command ("test", filename, plist)
Exemplo n.º 7
0
                ### Python 2.6 doesn't support `__func__` for classmethod
                orig_f = f
            else :
                orig_f.is_classmethod = cors is classmethod
            wrapper    = decorator (orig_f)
            decorated  = cors (wrapper)
            _update_wrapper (wrapper, orig_f)
        else :
            decorated = decorator (f)
            _update_wrapper (decorated, f)
        return decorated
    _update_wrapper (wrapper, decorator)
    return wrapper
# end def Decorator

_AR_undefined = TFL.Undef ("return-value")

def Annotated (RETURN = _AR_undefined, ** kw) :
    """Add dictionary `func_annotations` containing elements of `kw` and
       value of `RETURN` bound to key `return` as proposed by
       http://www.python.org/dev/peps/pep-3107/.

       Each key of `kw` must be the name of an argument of the function to be
       annotated::

           >>> from _TFL.portable_repr import portable_repr
           >>> @TFL.Annotated (bar = "Arg 1", baz = 42)
           ... def foo (bar, baz) : pass
           ...
           >>> portable_repr (foo.func_annotations)
           "{'bar' : 'Arg 1', 'baz' : 42}"
Exemplo n.º 8
0
class Base (TFL.Meta.Object) :
    """Query generator.

       Exceptions occurring during the evaluation of q-expressions are
       ignored if they match `Ignore_Exception`, i.e., per default, they
       aren't.

       To ignore exceptions, pass an Exception class or a tuple of
       exception classes to :meth:`Base.__init__`.

       Examples::

       >>> from _TFL.Record import Record as R
       >>> r1 = R (foo = 42, bar = 137, baz = 11, quux = R (a = 1, b = 200))
       >>> Q  = Base ()
       >>> QQ = Base (Ignore_Exception = (AttributeError, ))

       >>> (Q.foo == 42)
       Q.foo == 42
       >>> (Q.foo == 42) (r1)
       True
       >>> (Q.bar == 42) (r1)
       False
       >>> with expect_except (AttributeError) :
       ...     Q.qux (r1) is Q.undef
       AttributeError: qux
       >>> QQ.qux (r1) is QQ.undef
       True

    """

    class Ignore_Exception (Exception) :
        pass

    NOT              = TFL.Filter_Not

    undef            = TFL.Undef ("value")

    def __init__ (self, Ignore_Exception = None) :
        if Ignore_Exception is not None :
            self.Ignore_Exception = Ignore_Exception
    # end def __init__

    @property
    def DATE (self) :
        return self._Date_ (self._Date_.Date)
    # end def DATE

    @property
    def DATE_TIME (self) :
        return self._Date_ (self._Date_.Date_Time)
    # end def DATE_TIME

    @property
    def TIME (self) :
        return self._Date_ (self._Date_.Time)
    # end def TIME

    @property
    def NIL (self) :
        """Evaluates to None, no matter what object the q-expression is applied to."""
        return self._NIL_ (self)
    # end def NIL

    @property
    def SELF (self) :
        """Evaluates to the object the q-expression is applied to."""
        return self._Self_ (self)
    # end def SELF

    def AND (self, * args) :
        """Logical AND of `args`."""
        return self._AND_ (self, * args)
    # end def AND

    @Single_Dispatch_Method
    def APPLY (self, getter, * args) :
        result = getter
        if args :
            result = result (* args)
        return result
    # end def APPLY

    @APPLY.add_type (* pyk.string_types)
    def APPLY_string (self, s, * args) :
        getter = getattr (self, s)
        return self.APPLY (getter, * args)
    # end def APPLY_string

    def OR (self, * args) :
        """Logical OR of `args`."""
        return self._OR_  (self, * args)
    # end def OR

    def __getattr__ (self, name) :
        if name.startswith ("__") and name.endswith ("__") :
            ### Placate inspect.unwrap of Python 3.5,
            ### which accesses `__wrapped__` and eventually throws `ValueError`
            return getattr (self.__super, name)
        if "." in name :
            getter = getattr (TFL.Getter, name)
        else :
            getter = operator.attrgetter (name)
        return self._Get_ (self, name, getter)
    # end def __getattr__

    def __getitem__ (self, item) :
        assert not isinstance (item, slice)
        return self._Get_ (self, item, operator.itemgetter (item))
    # end def __getitem__

    def __bool__ (self) :
        return TypeError \
            ("Result of `%s` cannot be used in a boolean context" % (self, ))
Exemplo n.º 9
0
class Instance(_Base_):
    """Instance of selector for a choosen E_Type instance."""

    edit = TFL.Meta.Alias_Property("value")
    selected_p = True
    _outer = None
    _selected_type = TFL.Undef("selected_type")
    _undef = TFL.Undef("value")

    def __init__(self, completer, selector, **kw):
        self._completer = completer
        self._selector = selector
        for k, v in pyk.iteritems(kw):
            setattr(self, k, v)

    # end def __init__

    @Once_Property
    def elements(self):
        if self.selected_p:
            c = self._completer
            s = self._selector
            return tuple(e.instance(c, _outer=self) for e in s.elements)
        else:
            return ()

    # end def elements

    @property
    def selected_type(self):
        result = self._selected_type
        if TFL.is_undefined(result):
            outer = self._outer
            if outer is not None:
                result = self._selected_type = outer.selected_type
        return result

    # end def selected_type

    @selected_type.setter
    def selected_type(self, value):
        self._selected_type = value

    # end def selected_type

    @Once_Property
    @getattr_safe
    def value(self):
        obj = self._completer.obj
        if self._outer is None:
            return obj
        elif self.selected_p:
            return self._selector.AQ.QR(obj)
        else:
            return self._undef

    # end def value

    @Once_Property
    @getattr_safe
    def values(self):
        result = {}
        for _, e in self.level_elements():
            v = e.value
            if v and e.id:
                result[e.id] = v
        return result

    # end def values

    @Once_Property
    def _repr_tail(self):
        return "%s = %s" % (self._selector._repr_tail, self.value)

    # end def _repr_tail

    def __getattr__(self, name):
        if name.startswith("__") and name.endswith("__"):
            ### Placate inspect.unwrap of Python 3.5,
            ### which accesses `__wrapped__` and eventually throws `ValueError`
            return getattr(self.__super, name)
        result = getattr(self._selector, name)
        setattr(self, name, result)
        return result
Exemplo n.º 10
0
import _GTW._RST.Resource
import _GTW._RST.HTTP_Method
import _GTW._RST._MOM.Mixin

from   _MOM.import_MOM          import MOM, Q

from   _TFL._Meta.Once_Property import Once_Property
from   _TFL.Decorator           import getattr_safe
from   _TFL.pyk                 import pyk

import _TFL._Meta.Object
import _TFL.Undef

from   posixpath                import join as pp_join

_undef_arg = TFL.Undef ("arg")

@TFL.Add_Method (MOM.Attr._A_Id_Entity_)
def as_rest_cargo_raw \
        (self, obj, method, resource, request, response, seen, getter, a_name) :
    result = self.kind.get_value (obj)
    if result is not None :
        res_vet = resource.resource_from_e_type (result.type_name)
        url     = res_vet.href_obj (result)
        if (   request.has_option ("closure")
           and result.pid not in seen
           and res_vet.allow_method (method, request.user)
           ) :
            result = method._response_obj \
                ( resource, request, response, result, result.edit_attr, seen
                , getter, a_name
Exemplo n.º 11
0
#    26-Jan-2015 (CT) Add `update_combined__set` to force `rhs` to `set`
#     6-Mar-2015 (CT) Add `except` to `update_combined`, `update_combined__set`
#     5-Aug-2015 (CT) Add `Dont_Combine` to `__doc__`
#    ««revision-date»»···
#--

from   _TFL                       import TFL

from   _TFL._Meta.Single_Dispatch import Single_Dispatch, Single_Dispatch_2nd
from   _TFL.Decorator             import Attributed
from   _TFL.pyk                   import pyk

import _TFL._Meta.Object
import _TFL.Undef

_undef = TFL.Undef ("value")

class Dont_Combine (object) :
    """Mixin indicating that the value should replace an existing value,
       instead of combining with it.
    """
# end class Dont_Combine

class dict_dont_combine (Dont_Combine, dict) :
    """Dictionary that doesn't combine, but replaces, under `update_combined`"""
# end class dict_dont_combine

class list_dont_combine (Dont_Combine, list) :
    """List that doesn't combine, but replaces, under `update_combined`"""
# end class list_dont_combine
Exemplo n.º 12
0
 def __init__(self, source):
     self.source = source = iter(source)
     self._sentinel = self._succ = TFL.Undef("sentinel")