コード例 #1
0
ファイル: pylnk.py プロジェクト: vinnybod/Empire
 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
ファイル: lazy_import.py プロジェクト: ChenTzuYin/psychopy
    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
ファイル: entity.py プロジェクト: six8/springfield
 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
ファイル: tree.py プロジェクト: xboluna/astromodels
    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
ファイル: entity.py プロジェクト: six8/springfield
    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
ファイル: entity.py プロジェクト: six8/springfield
 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
ファイル: general.py プロジェクト: Darlingfuer/fanc
            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
ファイル: pathHelpers.py プロジェクト: ilastik/lazyflow
 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
ファイル: SharedData.py プロジェクト: lsst/ctrl_orca
    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
ファイル: utils.py プロジェクト: polyactis/pymodule
 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
ファイル: ice_simulator.py プロジェクト: mbus/m3-python
 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
ファイル: symbols.py プロジェクト: timtadh/pyflwor
 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
ファイル: configurableField.py プロジェクト: mmorage/DRAGONS
 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
ファイル: __init__.py プロジェクト: traverseda/Minecraft
    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
ファイル: configurableField.py プロジェクト: mmorage/DRAGONS
    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
ファイル: types.py プロジェクト: uchicago-cs/chisubmit
    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
ファイル: config.py プロジェクト: mmorage/DRAGONS
    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
ファイル: constraint.py プロジェクト: amolenaar/gaphas
 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
ファイル: utils.py プロジェクト: scudette/rekall
    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
ファイル: configurableField.py プロジェクト: mmorage/DRAGONS
    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
ファイル: simpleworkflows.py プロジェクト: dmitryzv/gbdxtools
    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)