Пример #1
0
 def __setattr__(self, key, value):
     if "_flags" not in self.__dict__:
         object.__setattr__(self, key, value)
     elif key in self.__dict__:
         object.__setattr__(self, key, value)
     else:
         self.__setitem__(key, value)
Пример #2
0
 def __setattr__(self, name, value):
     if name in self.__fields__:
         object.__setattr__(self, name, value)
     else:
         self.__values__[name] = value
         self.__flex_fields__.add(name)
         self.__changes__.add(name)
Пример #3
0
    def __setattr__(self, attr, value):
        if attr == "playlist":
            self.clearPlaylist()

            [self.enqueueFile(item.filename) for item in value]
        else:
            object.__setattr__(self, attr, value)
Пример #4
0
    def _resolve(self):
        """Return the real object for which this is a placeholder"""
        name = object.__getattribute__(self, '_name')
        real_obj = object.__getattribute__(self, '_real_obj')
        if real_obj is None:
            # No obj generated previously, so generate from factory and scope.
            factory = object.__getattribute__(self, '_factory')
            scope = object.__getattribute__(self, '_scope')
            obj = factory(self, scope, name)
            if obj is self:
                raise errors.IllegalUseOfScopeReplacer(name, msg="Object tried"
                    " to replace itself, check it's not using its own scope.")

            # Check if another thread has jumped in while obj was generated.
            real_obj = object.__getattribute__(self, '_real_obj')
            if real_obj is None:
                # Still no prexisting obj, so go ahead and assign to scope and
                # return. There is still a small window here where races will
                # not be detected, but safest to avoid additional locking.
                object.__setattr__(self, '_real_obj', obj)
                scope[name] = obj
                return obj

        # Raise if proxying is disabled as obj has already been generated.
        if not ScopeReplacer._should_proxy:
            raise errors.IllegalUseOfScopeReplacer(
                name, msg="Object already replaced, did you assign it"
                          " to another variable?")
        return real_obj
Пример #5
0
 def __setattr__(self, name, value):
     if name in self.__fields__:
         object.__setattr__(self, name, value)
     else:
         self.__values__[name] = value
         self.__flex_fields__.add(name)
         self.__changes__.add(name)
Пример #6
0
    def _resolve(self):
        """Return the real object for which this is a placeholder"""
        name = object.__getattribute__(self, '_name')
        real_obj = object.__getattribute__(self, '_real_obj')
        if real_obj is None:
            # No obj generated previously, so generate from factory and scope.
            factory = object.__getattribute__(self, '_factory')
            scope = object.__getattribute__(self, '_scope')
            obj = factory(self, scope, name)
            if obj is self:
                raise ValueError(name, msg="Object tried"
                    " to replace itself, check it's not using its own scope.")

            # Check if another thread has jumped in while obj was generated.
            real_obj = object.__getattribute__(self, '_real_obj')
            if real_obj is None:
                # Still no preexisting obj, so go ahead and assign to scope and
                # return. There is still a small window here where races will
                # not be detected, but safest to avoid additional locking.
                object.__setattr__(self, '_real_obj', obj)
                scope[name] = obj
                return obj

        # Raise if proxying is disabled as obj has already been generated.
        if not ScopeReplacer._should_proxy:
            raise ValueError(
                name, msg="Object already replaced, did you assign it"
                          " to another variable?")
        return real_obj
Пример #7
0
    def _set_parent(self, parent):

        # We need to use directly the __setattr__ method because the normal self._children = ... will trigger
        # an exception, because of the __setattr__ method of the DualAccessClass which forbids changing
        # nodes. However, this might reassign the parent to a class

        object.__setattr__(self, "_parent", parent)
Пример #8
0
    def __init__(self, ns, wdir=None, datatype=None):
        self.ns = ns
        if wdir == None:
            self.wdir = os.getcwd() + '/'
        else:
            self.wdir = wdir

        if datatype == None:
            datatype = 'dbl'

        self.ext = datatype
        if self.ext == 'dbl': self.extsize = 8
        if self.ext == 'flt': self.extsize = 4
        if self.ext == 'vtk': self.extsize = 4

        self.Header = {}
        try:
            self.GetParticleDataFileName()
        except (IOError):
            print("!ERROR! - Particle Data file not found : %s" % self.fname)
        else:
            if self.ext == 'vtk':
                Part_Data_dict = self.GetParticleDataVTK()
            else:
                self.ReadParticleFile()
                Part_Data_dict = self.GetParticleData()

            self.partdata_keys = []
            for keys in Part_Data_dict:
                self.partdata_keys.append(keys)
                object.__setattr__(self, keys, Part_Data_dict.get(keys))
Пример #9
0
 def __del__(self):
     if '_destroy' not in self.__dict__ or not self._destroy:
         return
     if '_handle' not in self.__dict__ or not self._handle:
         return
     self._free()
     object.__setattr__(self, '_handle', None)
Пример #10
0
 def __setattr__(self, key, value):
     if not key.startswith('_'):
         self._row[key] = value
         if self._auto_update:
             self._row.update()
     else:
         object.__setattr__(self, key, value)
Пример #11
0
    def __init__(self, **values):
        # Where the actual values are stored
        object.__setattr__(self, '__values__', {})

        # List of field names that have changed
        object.__setattr__(self, '__changes__', set([]))

        self.update(values)
Пример #12
0
 def __setattr__(self, name, value):
     """
     Don't allow setting attributes that haven't been defined as fields.
     """
     if name in self.__fields__:
         object.__setattr__(self, name, value)
     else:
         raise AttributeError('Field %r not defined.' % name)
Пример #13
0
def whereValue(val):
    '''
    returns the results of a Value function.
    '''
    def where(objs):
        return val(objs)
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #14
0
def booleanexprValue(value1, op, value2):
    '''
    returns the function which computes the result of boolean (and or) operation
    '''
    def where(objs):
        return op(value1, value2, objs)
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #15
0
    def __init__(self, **values):
        # Where the actual values are stored
        object.__setattr__(self, '__values__', {})

        # List of field names that have changed
        object.__setattr__(self, '__changes__', set([]))

        self.update(values)
Пример #16
0
            def __setattr__(self, key, value):
                if key == '_meta_attributes':
                    object.__setattr__(self, key, value)
                    return

                if self._meta_attributes is None:
                    raise t.FileModeError("File not writable, attribute cannot be set!")
                self._meta_attributes[key] = value
Пример #17
0
 def __setattr__(self, name, value):
     """
     Don't allow setting attributes that haven't been defined as fields.
     """
     if name in self.__fields__:
         object.__setattr__(self, name, value)
     else:
         raise AttributeError('Field %r not defined.' % name)
Пример #18
0
def dictValue(pairs):
    '''
    creates a dictionary from the passed pairs after evaluation.
    '''
    def dictval(objs):
        return dict((name(objs), value(objs)) for name, value in pairs)
    object.__setattr__(dictval, '__objquery__', True)
    return dictval
Пример #19
0
def listValue(values):
    '''
    creates a list from the pass objs after evaluation.
    '''
    def listval(objs):
        return list(value(objs) for value in values)
    object.__setattr__(listval, '__objquery__', True)
    return listval
Пример #20
0
def booleanValue(val):
    '''
    returns the function which booleanizes the result of the Value function
    '''
    def where(objs):
        return bool(val(objs))
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #21
0
 def __setattr__(self, key, value):
     try:
         object.__getattribute__(self, key)
         object.__setattr__(self, key, value)
     except AttributeError:
         if not self.cfg.has_section(self.section):
             self.cfg.add_section(self.section)
         self.cfg.set(self.section, key, value)
Пример #22
0
def setexprValue2(s1, op, s2):
    '''
    Returns a where function which returns the result of a set op set operation
    '''
    def where(objs):
        return op(s1(objs), s2(objs))
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #23
0
def unaryexprValue(op, val):
    '''
    returns the function which computes the result of boolean not operation
    '''
    def where(objs):
        return op(val(objs))
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #24
0
def setValue(s1, op, s2):
    '''
    Returns a Query function for the result of set operations (difference, union
    etc..)
    '''
    def query(glbls):
        return op(s1(glbls), s2(glbls))
    object.__setattr__(query, '__objquery__', True)
    return query
Пример #25
0
def setexprValue1(val, op, s):
    '''
    Returns a where function which returns the result of a value in set
    operation
    '''
    def where(objs):
        return op(val(objs), s(objs))
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #26
0
def arithValue(value1, op, value2):
    '''
    Returns a function which will calculate a where expression for a basic
    arithmetic operation.
    '''
    def arith_value(objs):
        return op(value1(objs), value2(objs))
    object.__setattr__(arith_value, '__objquery__', True)
    return arith_value
Пример #27
0
def comparisonValue(value1, op, value2):
    '''
    Returns a function which will calculate a where expression for a basic
    comparison operation.
    '''
    def where(objs):
        return op(value1(objs), value2(objs))
    object.__setattr__(where, '__objquery__', True)
    return where
Пример #28
0
 def __setattr__(self, attr, value):
     """
     This prevents us from accidentally writing to a non-existant attribute.
     e.g. if the user tries to say components.fIlEnAmE = 'newfile.h5', raise an error.
     """
     if hasattr(self, "_initialized"):
         # Attempt to get the old attribute first
         oldval = getattr(self, attr)
     object.__setattr__(self, attr, value)
Пример #29
0
    def __setattr__(self, name, value):
        if name == "_d" or len(self._d) == 0 or name in self.__dict__:
            object.__setattr__(self, name, value)
            return

        if not self._is_owned():
            raise AttributeError("%s: lock required for write access" % name)

        self._d[name] = value
Пример #30
0
    def __setattr__(self, name, value):
        if name == "_d" or len(self._d) == 0 or name in self.__dict__:
            object.__setattr__(self, name, value)
            return

        if not self._is_owned():
            raise AttributeError("%s: lock required for write access" % name)

        self._d[name] = value
Пример #31
0
 def __setattr__(self, attr, value):
     """
     This prevents us from accidentally writing to a non-existant attribute.
     e.g. if the user tries to say components.fIlEnAmE = 'newfile.h5', raise an error.
     """
     if hasattr(self, '_initialized'):
         # Attempt to get the old attribute first
         oldval = getattr(self, attr)
     object.__setattr__(self, attr, value)
Пример #32
0
def queryValue(q):
    '''
    Computes a path expression. The query (@q) is a list of attribute names and
    associated where expressions. The function returned computes the result when
    called.
    '''
    attrs = q
    def query(objs):
        def select(objs, attrs):
            '''a generator which computes the actual results'''
            def add(queue, u, v, i):
                '''adds the object v to the queue. It looks like u
                isn't necessary anymore. I should fix that...'''
                args = (v, '_objquery__i', i+1)
                try:
                    object.__setattr__(*args)
                except TypeError:
                    setattr(*args)
                except:
                    raise
                queue.appendleft(v)
            queue = deque()
            add(queue, None, type('base', (object,), objs), -1)
            while len(queue) > 0:
                u = queue.pop()
                i = object.__getattribute__(u, '_objquery__i')
                attrname, where = attrs[i]
                if hasattr(u, attrname): # the current object has the attr
                    v = getattr(u, attrname)
                    #it is iterable
                    if not isinstance(v, str) and hasattr(v, '__iter__'):
                        for z in v:
                            # add each child into the processing queue
                            if isinstance(v, dict):
                                next = KeyValuePair(z, v[z])
                            else:
                                next = z
                            # but only if its where condition is satisfied
                            if where != None:
                                cobjs = dict(objs)
                                cobjs.update({'self':next})
                                if not where(cobjs): continue
                            # if this is the last attribute yield the obj
                            if i+1 == len(attrs): yield next
                            else: add(queue, u, next, i) # otherwise add to the queue
                    else: #it is not iterable
                        if where != None:
                            cobjs = dict(objs)
                            cobjs.update({'self':v})
                            if not where(cobjs): continue
                        # if this is the last attribute yield the obj
                        if i+1 == len(attrs): yield v
                        else: add(queue, u, v, i) # otherwise add to the queue
        return OrderedSet(select(objs, attrs))
    object.__setattr__(query, '__objquery__', True)
    return query
Пример #33
0
    def __setattr__(self, key, value):
        """
    We want to prevent importers from adding invalid attributes (PWS-317)
    Rather fail hard in these cases.
    """
        if not hasattr(self, key):
            raise TypeError(
                "Cannot create attribute %s, Data is a frozen class" % key)

        object.__setattr__(self, key, value)
Пример #34
0
        def override_descriptor(name):
            def fn(self, *args, **kwargs):
                return self._descriptor_dict[name]

            # The first one is py2, the second py3
            try:
                object.__setattr__(self, name,
                                   MethodType(fn, self, type(self)))
            except TypeError:
                object.__setattr__(self, name, MethodType(fn, self))
Пример #35
0
 def __init__(self, conntrack, handle, msgtype=NFCT_T_UNKNOWN, destroy=True, attr=None):
     if not handle:
         raise RuntimeError("Empty entry handler")
     if not attr:
         attr = {}
     object.__setattr__(self, "_attr", attr)
     object.__setattr__(self, "_destroy", destroy)
     object.__setattr__(self, "_handle", handle)
     object.__setattr__(self, "_sub_system", conntrack)
     object.__setattr__(self, "_msgtype", msgtype)
Пример #36
0
 def __setattr__(self, name, value):
     """
     2012.11.24
     """
     try:
         attributeName2Index = object.__getattribute__(self, 'attributeName2Index')
         attributeName2Index[name] = len(self)
         self.append(value)
     except AttributeError:
         object.__setattr__(self, name, value)
Пример #37
0
 def __setattr__(self, name, value):
     if name is 'direction':
         if value not in (Gpio.GPIO_INPUT, Gpio.GPIO_OUTPUT, Gpio.GPIO_TRISTATE):
             raise ValueError("Attempt to set illegal direction {}".format(value))
     if name is 'level':
         if value not in (True, False):
             raise ValueError("GPIO level must be true or false. Got {}".format(value))
     if name is 'interrupt':
         if value not in (True, False):
             raise ValueError("GPIO interrupt must be true or false. Got {}".format(value))
     object.__setattr__(self, name, value)
Пример #38
0
 def add(queue, u, v, i):
     '''adds the object v to the queue. It looks like u
     isn't necessary anymore. I should fix that...'''
     args = (v, '_objquery__i', i+1)
     try:
         object.__setattr__(*args)
     except TypeError:
         setattr(*args)
     except:
         raise
     queue.appendleft(v)
Пример #39
0
 def __initValue(self, at, label):
     """
     if field.default is an instance of ConfigClass, custom construct
     _value with the correct values from default.
     otherwise call ConfigClass constructor
     """
     name = _joinNamePath(self._config._name, self._field.name)
     if type(self._field.default) == self.ConfigClass:
         storage = self._field.default._storage
     else:
         storage = {}
     value = self._ConfigClass(__name=name, __at=at, __label=label, **storage)
     object.__setattr__(self, "_value", value)
Пример #40
0
    def __setattr__(self, name, value):
        try:
            setattr(self._module, name, value)
        except AttributeError:
            if self._module is not None:
                raise

            import_name = 'pyglet.%s' % self._module_name
            __import__(import_name)
            module = sys.modules[import_name]
            object.__setattr__(self, '_module', module)
            globals()[self._module_name] = module
            setattr(module, name, value)
Пример #41
0
    def __setattr__(self, name, value, at=None, label="assignment"):
        """
        Pretend to be an isntance of  ConfigClass.
        Attributes defined by ConfigurableInstance will shadow those defined in ConfigClass
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")

        if name in self.__dict__:
            # attribute exists in the ConfigurableInstance wrapper
            object.__setattr__(self, name, value)
        else:
            if at is None:
                at = getCallStack()
            self._value.__setattr__(name, value, at=at, label=label)
Пример #42
0
    def __setattr__(self, name, value):
        if self.__is_relationship_attr("_rel_" + name):
            raise AttributeNotEditableException(name, value)

        api_attr = self.__get_api_attr(name)
        if api_attr is None:        
            object.__setattr__(self, name, value)
        else:
            if not api_attr.editable:
                raise AttributeNotEditableException(name, value)
            else:
                if self._api_client._deferred_save:
                    self.dirty[name] = True
                else:
                    self.edit(**{name: value})                
                object.__setattr__(self, name, value)
Пример #43
0
    def __setattr__(self, attr, value, at=None, label="assignment"):
        """!Regulate which attributes can be set

        Unlike normal python objects, Config objects are locked such
        that no additional attributes nor properties may be added to them
        dynamically.

        Although this is not the standard Python behavior, it helps to
        protect users from accidentally mispelling a field name, or
        trying to set a non-existent field.
        """
        if attr in self._fields:
            if at is None:
                at = getCallStack()
            # This allows Field descriptors to work.
            self._fields[attr].__set__(self, value, at=at, label=label)
        elif hasattr(getattr(self.__class__, attr, None), '__set__'):
            # This allows properties and other non-Field descriptors to work.
            return object.__setattr__(self, attr, value)
        elif attr in self.__dict__ or attr in ("_name", "_history", "_storage", "_frozen", "_imports"):
            # This allows specific private attributes to work.
            self.__dict__[attr] = value
        else:
            # We throw everything else.
            raise AttributeError("%s has no attribute %s" % (_typeStr(self), attr))
Пример #44
0
 def __setattr__(self, name, value):
     """
     Sets function argument values.
     """
     # Note - once self._args is created, no new attributes can
     # be added to self.__dict__.  This is a good thing as it throws
     # an exception if you try to assign to an arg which is inappropriate
     # for the function in the solver.
     if "_args" in self.__dict__:
         if name in self._args:
             self._args[name] = value
         elif name in self.__dict__:
             self.__dict__[name] = value
         else:
             raise KeyError(name)
     else:
         object.__setattr__(self, name, value)
Пример #45
0
    def __setattr__(self, attr, value):
        try:
            # Check that the object itself has this attribute.
            object.__getattribute__(self, attr)

            return object.__setattr__(self, attr, value)
        except AttributeError:
            self.Set(attr, value)
Пример #46
0
    def retarget(self, target, ConfigClass=None, at=None, label="retarget"):
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")

        try:
            ConfigClass = self._field.validateTarget(target, ConfigClass)
        except BaseException as e:
            raise FieldValidationError(self._field, self._config, e.message)

        if at is None:
            at = getCallStack()
        object.__setattr__(self, "_target", target)
        if ConfigClass != self.ConfigClass:
            object.__setattr__(self, "_ConfigClass", ConfigClass)
            self.__initValue(at, label)

        history = self._config._history.setdefault(self._field.name, [])
        msg = "retarget(target=%s, ConfigClass=%s)" % (_typeStr(target), _typeStr(ConfigClass))
        history.append((msg, at, label))
Пример #47
0
    def __setattr__(self, k, v):
        if k == "task":
            object.__setattr__(self, k, v)
            return

        # special attributes for internal use
        if k in ['_portnames']:
            object.__setattr__(self, k, v)
            return

        # special handling for setting port values
        if k in self._portnames and hasattr(self, k):
            # parse batch inputs vs regular
            batch_values = []

            # if input type is of list, use batch workflows endpoint
            if isinstance(v, list):
                self.__getattribute__(k).value = "$batch_value:{0}".format(
                    "batch_input_{0}".format(k))
                batch_values.append({"name": "batch_input_{0}".format(k), "values": v})
            else:
                port = self.__getattribute__(k)
                port.value = v
                return

            # set the batch values object
            if batch_values:
                self.task.batch_values = batch_values
            else:
                self.task.batch_values = None
            return

        # find out if this is a valid multiplex port, i.e. this portname is prefixed by a multiplex port
        mp_port = self.get_matching_multiplex_port(k)
        if mp_port:
            new_multiplex_port = Port(
                k,
                mp_port.type,
                mp_port.required,
                mp_port.description,
                value=v
            )
            object.__setattr__(self, k, new_multiplex_port)
            self._portnames.update([k])
            return

        # default for initially setting up ports
        if k in self._portnames:
            object.__setattr__(self, k, v)
        else:
            raise AttributeError('Task has no input port named %s.' % k)
Пример #48
0
    def __setattr__(self, k, v):
        # special attributes for internal use
        if k in ['_portnames']:
            object.__setattr__(self, k, v)
            return

        # special handling for setting port values
        if k in self._portnames and hasattr(self, k):
            port = self.__getattribute__(k)
            port.value = v
            return

        # find out if this is a valid multiplex port, i.e. this portname is prefixed by a multiplex port
        mp_port = self.get_matching_multiplex_port(k)
        if mp_port:
            new_multiplex_port = Port(
                k,
                mp_port.type, 
                mp_port.required, 
                mp_port.description, 
                value=v
            )
            object.__setattr__(self, k, new_multiplex_port)
            self._portnames.update([k])
            return

        # default for initially setting up ports
        if k in self._portnames:
            object.__setattr__(self, k, v)
        else:
            raise AttributeError('Task has no input port named %s.' % k)