Esempio n. 1
0
    def __getattribute__(self, k):
        """
        Overwride getattribute for multiplex ports.  If we try to get a port for which a multiplex port
        is a prefix, create the port object and then return it.
        """
        # handle regular properties or internal methods normally
        if k in ['_portnames', '_task_name', 'get_matching_multiplex_port'] or k.startswith('__'):
            return object.__getattribute__(self, k)

        # if this port already exists, retrieve it
        if k in self._portnames:
            return object.__getattribute__(self, k)

        # determine if we're trying to get the value for a multiplex output port
        if not k in self._portnames:
            mp_port = self.get_matching_multiplex_port(k)
            if mp_port:
                self.__setattr__(
                    k,
                    Port(
                        mp_port.name,
                        mp_port.type,
                        mp_port.required,
                        mp_port.description,
                        value="source:" + self._task_name + ":" + k,
                        is_input_port=False,
                        is_multiplex=False
                        )
                    )
                self._portnames.update([k])

        return object.__getattribute__(self, k)
Esempio n. 2
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
Esempio n. 3
0
    def __getattribute__(self, k):
        """
        Overwride getattribute for multiplex ports.  If we try to get a port for which a multiplex port
        is a prefix, create the port object and then return it.
        """
        # handle regular properties or internal methods normally
        if k in ['_portnames', '_task_name', 'get_matching_multiplex_port'] or k.startswith('__'):
            return object.__getattribute__(self, k)

        # if this port already exists, retrieve it
        if k in self._portnames:
            return object.__getattribute__(self, k)

        # determine if we're trying to get the value for a multiplex output port
        if not k in self._portnames:
            mp_port = self.get_matching_multiplex_port(k)
            if mp_port:
                self.__setattr__(
                    k,
                    Port(
                        mp_port.name,
                        mp_port.type,
                        mp_port.required,
                        mp_port.description,
                        value="source:" + self._task_name + ":" + k,
                        is_input_port=False,
                        is_multiplex=False
                        )
                    )
                self._portnames.update([k])

        return object.__getattribute__(self, k)
Esempio n. 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 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
Esempio n. 5
0
    def _import(self, scope, name):
        children = object.__getattribute__(self, '_import_replacer_children')
        member = object.__getattribute__(self, '_member')
        module_path = object.__getattribute__(self, '_module_path')
        module_python_path = '.'.join(module_path)
        if member is not None:
            module = __import__(module_python_path,
                                scope,
                                scope, [member],
                                level=0)
            return getattr(module, member)
        else:
            module = __import__(module_python_path, scope, scope, [], level=0)
            for path in module_path[1:]:
                module = getattr(module, path)

        # Prepare the children to be imported
        for child_name, (child_path, child_member, grandchildren) in \
                children.items():
            # Using self.__class__, so that children get children classes
            # instantiated. (This helps with instrumented tests)
            cls = object.__getattribute__(self, '__class__')
            cls(module.__dict__,
                name=child_name,
                module_path=child_path,
                member=child_member,
                children=grandchildren)
        return module
Esempio n. 6
0
 def __getattr__(self, name):
   if TASK_SERVER.ENABLED.get() and hasattr(ntasks, name):
     attr = object.__getattribute__(ntasks, name)
     def _method(*args, **kwargs):
       return attr(*args, **dict(kwargs, postdict=self.request.POST, user_id=self.request.user.id))
     return _method
   else:
     return object.__getattribute__(self.api, name)
Esempio n. 7
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)
Esempio n. 8
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)
Esempio n. 9
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)
Esempio n. 10
0
 def __getattribute__(self, name):
     """
     2012.11.24
     """
     try:
         returnAttr = object.__getattribute__(self, name)
     except AttributeError:
         attributeName2Index = object.__getattribute__(self, 'attributeName2Index')
         index = attributeName2Index.get(name, None)
         if index is not None:
             returnAttr =  self.__getitem__(index)
         else:
             returnAttr = None
     return returnAttr
Esempio n. 11
0
 def __getattr__(self, val):
     if val == "Attributes":
         attrs = {}
         #materializing dynamic properties and adding them to main dictionary
         for attr in self.__attributes__:
             if type(
                     self.__attributes__[attr]
             ) == types.NoneType:  #skipping all attributes that are empty
                 pass
             elif type(self.__attributes__[attr]) in [
                     types.MethodType, types.FunctionType
             ]:
                 try:
                     attrs[attr] = self.__attributes__[attr]()
                 except:  #in case function relies on external object that has not been initialized yet
                     pass
             else:
                 attrs[attr] = self.__attributes__[attr]
         return attrs
     elif val in self.__attributes__:
         if type(self.__attributes__[val]) in [
                 types.MethodType, types.FunctionType
         ]:
             return self.__attributes__[val]()
         else:
             return self.__attributes__[val]
     else:
         return object.__getattribute__(self, val)
         raise AttributeError("Property: %s does not exist" % val)
Esempio n. 12
0
    def __getattribute__(self, name):
        if name == "_d" or len(self._d) == 0 or name not in self._d:
            return object.__getattribute__(self, name)

        if self._lockOnRead and not self._is_owned():
            raise AttributeError("%s: lock required for read access" % name)
        return self._d[name]
Esempio n. 13
0
    def __getattribute__(self, name):
        if name == "_d" or len(self._d) == 0 or name not in self._d:
            return object.__getattribute__(self, name)

        if self._lockOnRead and not self._is_owned():
            raise AttributeError("%s: lock required for read access" % name)
        return self._d[name]
Esempio n. 14
0
    def __getattribute__(self, item):

        # White list of available attributes
        if item in ["__deepcopy__", "to_pandas"]:

            return object.__getattribute__(self, item)

        raise InvalidPSFError("Trying to use an invalid PSF")
Esempio n. 15
0
 def __getattr__(self, bandname):
     """
     Override _gettattr__() for bandnames in self.bandlabels.
     """
     if bandname in self.bandlabels:
         return self.dataobj['All_Data/' + self.bandlabels[bandname]]
     else:
         return object.__getattribute__(self, bandname)
 def __getattr__(self, name):
     # Special methods which may be accessed before the object is
     # fully constructed (e.g. in unpickling).
     if name[:2] == name[-2:] == '__':
         return object.__getattribute__(self, name)
     elif name in self._visible_option_list():
         return self._all_options[name]
     else:
         raise AttributeError("'%s' object has no attribute '%s'" %
                              (type(self).__name__, name))
Esempio n. 17
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)
 def __getattr__(self, name):
   # Special methods which may be accessed before the object is
   # fully constructed (e.g. in unpickling).
   if name[:2] == name[-2:] == '__':
     return object.__getattribute__(self, name)
   elif name in self._visible_option_list():
     return self._all_options.get(name, getattr(self._visible_options, name))
   else:
     raise AttributeError("'%s' object has no attribute '%s'" %
                          (type(self).__name__, name))
Esempio n. 19
0
    def __getattribute__(self, name):
        attr = object.__getattribute__(self, name)
        if name.startswith('_') or not callable(attr):
            return attr

        @lock
        def wrapper(*args, **kwargs):
            return attr(*args[1:], **kwargs)

        return wrapper
Esempio n. 20
0
 def __getattribute__(self, key):
     common = object.__getattribute__(self, 'common_keys')
     mapped = object.__getattribute__(self, 'mapped_keys')
     if key in mapped:
         lk, maker = mapped[key]
         if self._legacy:
             if lk is None:
                 result = None if maker is None else maker()
             else:
                 result = self._legacy.get(lk)
         else:
             value = None if maker is None else maker()
             if key not in ('commands', 'exports', 'modules', 'namespaces',
                            'classifiers'):
                 result = self._data.get(key, value)
             else:
                 # special cases for PEP 459
                 sentinel = object()
                 result = sentinel
                 d = self._data.get('extensions')
                 if d:
                     if key == 'commands':
                         result = d.get('python.commands', value)
                     elif key == 'classifiers':
                         d = d.get('python.details')
                         if d:
                             result = d.get(key, value)
                     else:
                         d = d.get('python.exports')
                         if not d:
                             d = self._data.get('python.exports')
                         if d:
                             result = d.get(key, value)
                 if result is sentinel:
                     result = value
     elif key not in common:
         result = object.__getattribute__(self, key)
     elif self._legacy:
         result = self._legacy.get(key)
     else:
         result = self._data.get(key)
     return result
Esempio n. 21
0
 def __getattribute__(self, name):
     try:
         # If we have this attr, use it.
         # (e.g. self.mp_file, self._internal_path, etc.)
         return object.__getattribute__(self, name)
     except:
         # Briefly open the file and read the attribute directly from h5py
         with h5py.File(self.mp_file._filepath, "r") as f:
             val = getattr(f[self._internal_path], name)
             assert not callable(val), "MultiprocessingHdf5File Groups cannot provide access to callable items."
             return copy.copy(val)
Esempio n. 22
0
 def __getattribute__(self, name):
     try:
         # If we have this attr, use it.
         # (e.g. self.mp_file, self._internal_path, etc.)
         return object.__getattribute__(self, name)
     except:
         # Briefly open the file and read the attribute directly from h5py
         with h5py.File(self.mp_file._filepath) as f:
             val = getattr(f[self._internal_path], name)
             assert not callable(val), "MultiprocessingHdf5File Groups cannot provide access to callable items."
             return copy.copy(val)
Esempio n. 23
0
 def __getattribute__(self, item):
     if '.' in item:
         parts = item.split('.')
         field = Entity.__getattribute__(self, parts[0])
         if isinstance(field, list):
             array = field
             return [getattr(a, parts[1]) for a in array]
         else:
             return getattr(field, parts[1])
     else:
         return object.__getattribute__(self, item)
Esempio n. 24
0
    def __init__(self, *args, **kwargs):
        """
        Sets up the objects' internal column.
        Tests for the presence of a primary key, and attempts to load a
        description using it.
        """

        if 'config' in kwargs:
            config = kwargs['config']
            del (kwargs['config'])
        else:
            config = None

        if 'handle' in kwargs:
            handle = kwargs['handle']
            del (kwargs['handle'])
        else:
            handle = None

        if args or kwargs:
            d_out("SimpleModel.__init__: Got args of %s" % repr(args))
            d_out("SimpleModel.__init__: Got kwargs of %s" % repr(kwargs))

        #
        # If the type defines a base type, the base instance will be
        # passed in the 'base_' kwarg: merge the base attrs into
        # kwargs and hand over to superclass.
        #
        SimpleModel.merge_base_attrs(kwargs)

        #
        # Initialize table attrs by copying from keyword arguments.
        #
        # This makes sure the objects not loaded from DB has at least
        # the None values in attrs and access to them doesn't raise.
        #
        if hasattr(self, 'table'):
            for name in self.table:
                self.__dict__[name] = kwargs.get(name, None)

        # should automatically pick up config= and handle=
        super(SimpleModel, self).__init__(config, handle, *args, **kwargs)

        if hasattr(self, 'loaded_indicator') and self.__dict__.get(
                object.__getattribute__(self, 'loaded_indicator')) is not None:
            self._loaded = True
        else:
            self._loaded = False

        # config and handle have been dealt with, now.
        if not self._loaded and hasattr(self, '__load__'):
            if args or kwargs:
                self.__load_by_key__(*args, **kwargs)
Esempio n. 25
0
    def __init__(self, *args, **kwargs):
        """
        Sets up the objects' internal column.
        Tests for the presence of a primary key, and attempts to load a
        description using it.
        """

        if 'config' in kwargs:
            config = kwargs['config']
            del(kwargs['config'])
        else:
            config = None

        if 'handle' in kwargs:
            handle = kwargs['handle']
            del(kwargs['handle'])
        else:
            handle = None

        if args or kwargs:
            d_out("SimpleModel.__init__: Got args of %s" % repr(args))
            d_out("SimpleModel.__init__: Got kwargs of %s" % repr(kwargs))

        #
        # If the type defines a base type, the base instance will be
        # passed in the 'base_' kwarg: merge the base attrs into
        # kwargs and hand over to superclass.
        #
        SimpleModel.merge_base_attrs(kwargs)

        #
        # Initialize table attrs by copying from keyword arguments.
        #
        # This makes sure the objects not loaded from DB has at least
        # the None values in attrs and access to them doesn't raise.
        #
        if hasattr(self, 'table'):
            for name in self.table:
                self.__dict__[name] = kwargs.get(name, None)

        # should automatically pick up config= and handle=
        super(SimpleModel, self).__init__(config, handle, *args, **kwargs)

        if hasattr(self, 'loaded_indicator') and self.__dict__.get(object.__getattribute__(self, 'loaded_indicator')) is not None:
            self._loaded = True
        else:
            self._loaded = False

        # config and handle have been dealt with, now.
        if not self._loaded and hasattr(self, '__load__'):
            if args or kwargs:
                self.__load_by_key__(*args, **kwargs)
Esempio n. 26
0
 def __delattr__(self, name):
     """
     2012.11.24
     """
     try:
         attributeName2Index = object.__getattribute__(self, 'attributeName2Index')
         index = attributeName2Index.get(name, None)
         if index is not None:
             del attributeName2Index[name]
             list.__delitem__(self, index)
             #self.pop(index)
     except AttributeError:
         object.__delattr__(self, name)
Esempio n. 27
0
 def __getitem__(self, index_or_key):
     """
     2012.12.20 enable it to retrieve item using either index or
         attributeName (like a dictionary).
     i.e. pdata[0] or pdata['chromosome'] is equivalent if attribute 0 is
          chromosome.
     """
     if type(index_or_key)==int:
         return list.__getitem__(self, index_or_key)
     else:
         attributeName2Index = object.__getattribute__(self, 'attributeName2Index')
         index = attributeName2Index.get(index_or_key, None)
         return list.__getitem__(self, index)
Esempio n. 28
0
    def section_(self, sectionName):
        """
        _section_

        Get a section by name, create it if not present,
        returns a ConfigSection instance

        """
        if sectionName in self.__dict__:
            return self.__dict__[sectionName]
        newSection = ConfigSection(sectionName)
        self.__setattr__(sectionName, newSection)
        return object.__getattribute__(self, sectionName)
Esempio n. 29
0
 def __setattr__(self, key, value):
     self._validate_value(key, value)
     common = object.__getattribute__(self, 'common_keys')
     mapped = object.__getattribute__(self, 'mapped_keys')
     if key in mapped:
         lk, _ = mapped[key]
         if self._legacy:
             if lk is None:
                 raise NotImplementedError
             self._legacy[lk] = value
         elif key not in ('commands', 'exports', 'modules', 'namespaces',
                          'classifiers'):
             self._data[key] = value
         else:
             # special cases for PEP 459
             d = self._data.setdefault('extensions', {})
             if key == 'commands':
                 d['python.commands'] = value
             elif key == 'classifiers':
                 d = d.setdefault('python.details', {})
                 d[key] = value
             else:
                 d = d.setdefault('python.exports', {})
                 d[key] = value
     elif key not in common:
         object.__setattr__(self, key, value)
     else:
         if key == 'keywords':
             if isinstance(value, string_types):
                 value = value.strip()
                 if value:
                     value = value.split()
                 else:
                     value = []
         if self._legacy:
             self._legacy[key] = value
         else:
             self._data[key] = value
Esempio n. 30
0
    def _import(self, scope, name):
        children = object.__getattribute__(self, '_import_replacer_children')
        member = object.__getattribute__(self, '_member')
        module_path = object.__getattribute__(self, '_module_path')
        module_python_path = '.'.join(module_path)
        if member is not None:
            module = __import__(module_python_path, scope, scope, [member], level=0)
            return getattr(module, member)
        else:
            module = __import__(module_python_path, scope, scope, [], level=0)
            for path in module_path[1:]:
                module = getattr(module, path)

        # Prepare the children to be imported
        for child_name, (child_path, child_member, grandchildren) in \
                children.items():
            # Using self.__class__, so that children get children classes
            # instantiated. (This helps with instrumented tests)
            cls = object.__getattribute__(self, '__class__')
            cls(module.__dict__, name=child_name,
                module_path=child_path, member=child_member,
                children=grandchildren)
        return module
Esempio n. 31
0
    def __getattribute__(self, name):

        try:
            methods = object.__getattribute__(self, 'methods')
        except AttributeError:
            pass
        else:
            if name in methods:
                f = lambda *args, **kwargs: self._scrape(name, *args, **kwargs)
                f.__name__ = name
                f.__doc__ = getattr(next(self.iterscrapers(name)),
                                    name).__doc__
                return f
        return super(Scrape, self).__getattribute__(name)
Esempio n. 32
0
    def __getattribute__(self, name):
        try:
            # If we have this attr, use it.
            # (e.g. self.mp_file, self._internal_path, etc.)
            return object.__getattribute__(self, name)
        except:
            # Briefly open the file and read the attribute directly from h5py
            with h5py.File(self.mp_file._filepath, "r") as f:
                val = getattr(f[self._internal_path], name)
                assert not callable(val), "MultiprocessingHdf5File Datasets cannot provide access to callable items."

                # Special case: copy hdf5 dataset attrs into a dict
                if name == "attrs":
                    val = dict(list(val.items()))
                return val
Esempio n. 33
0
    def __getattribute__(self, name):
        try:
            # If we have this attr, use it.
            # (e.g. self.mp_file, self._internal_path, etc.)
            return object.__getattribute__(self, name)
        except:
            # Briefly open the file and read the attribute directly from h5py
            with h5py.File(self.mp_file._filepath) as f:
                val = getattr(f[self._internal_path], name)
                assert not callable(val), "MultiprocessingHdf5File Datasets cannot provide access to callable items."

                # Special case: copy hdf5 dataset attrs into a dict
                if name == "attrs":
                    val = dict(list(val.items()))
                return val
Esempio n. 34
0
 def __delitem__(self, indexToDelete):
     """
     2012.11.24
     
     """
     list.__delitem__(self, indexToDelete)
     try:
         attributeName2Index = object.__getattribute__(self, 'attributeName2Index')
         attributeToBeDeleted = None		
         for attributeName, index in attributeName2Index.items():
             if index==indexToDelete:
                 attributeToBeDeleted = attributeName
                 break
         if attributeToBeDeleted is not None:
             del attributeName2Index[attributeToBeDeleted]
     except AttributeError:
         pass
Esempio n. 35
0
 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
Esempio n. 36
0
    def __init__(self, scope, name, module_path, member=None, children={}):
        """Upon request import 'module_path' as the name 'module_name'.
        When imported, prepare children to also be imported.

        :param scope: The scope that objects should be imported into.
            Typically this is globals()
        :param name: The variable name. Often this is the same as the
            module_path. 'bzrlib'
        :param module_path: A list for the fully specified module path
            ['bzrlib', 'foo', 'bar']
        :param member: The member inside the module to import, often this is
            None, indicating the module is being imported.
        :param children: Children entries to be imported later.
            This should be a map of children specifications.
            ::
            
                {'foo':(['bzrlib', 'foo'], None,
                    {'bar':(['bzrlib', 'foo', 'bar'], None {})})
                }

        Examples::

            import foo => name='foo' module_path='foo',
                          member=None, children={}
            import foo.bar => name='foo' module_path='foo', member=None,
                              children={'bar':(['foo', 'bar'], None, {}}
            from foo import bar => name='bar' module_path='foo', member='bar'
                                   children={}
            from foo import bar, baz would get translated into 2 import
            requests. On for 'name=bar' and one for 'name=baz'
        """
        if (member is not None) and children:
            raise ValueError('Cannot supply both a member and children')

        object.__setattr__(self, '_import_replacer_children', children)
        object.__setattr__(self, '_member', member)
        object.__setattr__(self, '_module_path', module_path)

        # Indirecting through __class__ so that children can
        # override _import (especially our instrumented version)
        cls = object.__getattribute__(self, '__class__')
        ScopeReplacer.__init__(self,
                               scope=scope,
                               name=name,
                               factory=cls._import)
Esempio n. 37
0
    def __init__(self, scope, name, module_path, member=None, children={}):
        """Upon request import 'module_path' as the name 'module_name'.
        When imported, prepare children to also be imported.

        :param scope: The scope that objects should be imported into.
            Typically this is globals()
        :param name: The variable name. Often this is the same as the
            module_path. 'bzrlib'
        :param module_path: A list for the fully specified module path
            ['bzrlib', 'foo', 'bar']
        :param member: The member inside the module to import, often this is
            None, indicating the module is being imported.
        :param children: Children entries to be imported later.
            This should be a map of children specifications.
            ::
            
                {'foo':(['bzrlib', 'foo'], None,
                    {'bar':(['bzrlib', 'foo', 'bar'], None {})})
                }

        Examples::

            import foo => name='foo' module_path='foo',
                          member=None, children={}
            import foo.bar => name='foo' module_path='foo', member=None,
                              children={'bar':(['foo', 'bar'], None, {}}
            from foo import bar => name='bar' module_path='foo', member='bar'
                                   children={}
            from foo import bar, baz would get translated into 2 import
            requests. On for 'name=bar' and one for 'name=baz'
        """
        if (member is not None) and children:
            raise ValueError('Cannot supply both a member and children')

        object.__setattr__(self, '_import_replacer_children', children)
        object.__setattr__(self, '_member', member)
        object.__setattr__(self, '_module_path', module_path)

        # Indirecting through __class__ so that children can
        # override _import (especially our instrumented version)
        cls = object.__getattribute__(self, '__class__')
        ScopeReplacer.__init__(self, scope=scope, name=name,
                               factory=cls._import)
Esempio n. 38
0
 def __setattr__(self, attr, value):
     obj = object.__getattribute__(self, '_resolve')()
     return setattr(obj, attr, value)
Esempio n. 39
0
 def __call__(self, *args, **kwargs):
     obj = object.__getattribute__(self, '_resolve')()
     return obj(*args, **kwargs)
Esempio n. 40
0
 def __getattribute__(self, attr):
     if attr in ['from_file', 'from_string']:
         return self.__get_wrapped_with_postprocessors(
             object.__getattribute__(self, attr))
     return object.__getattribute__(self, attr)
Esempio n. 41
0
 def __getattr__(self, name):
     # Any enchant we haven't assigned a value to, we don't have.
     if name in self.allowed_melee_enchants:
         return False
     object.__getattribute__(self, name)
Esempio n. 42
0
 def __getattribute__(self, attr):
     if attr in ['from_file', 'from_string']:
         return self.__get_wrapped_with_postprocessors(object.__getattribute__(self, attr))
     return object.__getattribute__(self, attr)
Esempio n. 43
0
File: proxyfs.py Progetto: mapr/hue
 def __getattr__(self, item):
   return getattr(object.__getattribute__(self, "_default_fs"), item)
 def __getattr__(self, name):
     object.__getattribute__(self, name)
Esempio n. 45
0
 def __getattr__(self, name):
     # Any racial we haven't assigned a value to, we don't have.
     if name in self.allowed_racials:
         return False
     else:
         object.__getattribute__(self, name)
Esempio n. 46
0
 def __getattribute__(self, attr):
     obj = object.__getattribute__(self, '_resolve')()
     return getattr(obj, attr)
Esempio n. 47
0
    def __getattribute__(self,name):

        """
        Private method.

        This function tests all attributes of the *SimpleModel* if they are
        instances of *meta_query*.
        If they are a *meta_query*, columns from the Model are mapped
        to the InstanceMethods' arguments, as appropriate.
        """

        attr = object.__getattribute__(self,name)
        if name == '__load__':
            d_out("skipping: %s" % name)
            return attr

        if attr is None and name in object.__getattribute__(self, 'table') and not object.__getattribute__(self,'_loaded'):
            should_lazyload = hasattr(self,'__lazyload__')
        else:
            should_lazyload = False

        if should_lazyload:
            d_out("lazyloading {0} on {1}".format(self.__class__, name))
            attrs = object.__getattribute__(self, '__dict__')
            attrs['_loaded'] = True
            rs = self.__lazyload__(options={'handle':self.handle})
            if not rs:
                raise NotFoundError("__lazyload__ returned: {0}".format(rs))
            if isinstance(rs, psycopg2.extras.DictRow):
                loaded_attrs = dict(rs)
            elif isinstance(rs, SimpleModel):
                #python 2.7+:
                #loaded_attrs = {_ for _ in rs.__dict__.iteritems() if _[0] in self.table}
                loaded_attrs = {}
                for col in self.table:
                    loaded_attrs[col] = rs.__dict__[col]
            else:
                raise Exception("__lazyload__ returned unexpected type: {0}".format(type(rs)))
            SimpleModel.merge_base_attrs(loaded_attrs)
            attrs.update(loaded_attrs)
            return attrs[name]

        if isinstance(attr, meta_query):

            d_out("SimpleModel.__getattribute__: Found meta_query %s" % name)
            def instance(*args,**kwargs):

                if args:
                    raise FunctionError("This function can only take keyword arguments.")
                my_args = kwargs.copy()
                d_out("SimpleModel.__getattribute__ InstanceMethod: kwargs: %s" % repr(kwargs))
                d_out("SimpleModel.__getattribute__ InstanceMethod: self.__dict__: %s" % self.__dict__)
                for arg in attr.args:
                    d_out("SimpleModel.__getattribute__ InstanceMethod: checking arg %s" % arg)
                    if arg not in kwargs:
                        d_out("not in my_args")
                        if hasattr(self, arg):
                            d_out("SimpleModel.__getattribute__ InstanceMethod: found %s in col.." % arg)
                            my_args[arg] = getattr(self, arg)
                        else:
                            my_args[arg] = None

                if 'options' not in kwargs:
                    d_out("SimpleModel.__getattribute__ InstanceMethod: Didn't find options.")
                    my_args['options'] = {}

                # pass self to the query object
                my_args['options']['model'] = self

                d_out("SimpleModel.__getattribute__: InstanceMethod: Setting handle.")
                my_args['options']['handle'] = self.handle
                rs = attr(*args, **my_args)
                d_out("SimpleModel.__getattribute__: InstanceMethod: model :{model} attrib name: {name} (attrib value: {value}) constructor returned {rs}".format(model=self, name=name, value=attr, rs=rs))
                return rs

            if attr.is_property:
                return instance()
            else:
                return instance

        else:
            return attr
Esempio n. 48
0
 def __getattr__(self, proc):
     # Any proc we haven't assigned a value to, we don't have.
     if proc in self.allowed_procs:
         return False
     object.__getattribute__(self, proc)
Esempio n. 49
0
 def __getattr__(self, name):
     # If someone tries to access a talent not initialized (the talent
     # string was shorter than 6) we return False
     if name in self.allowed_talents:
         return False
     object.__getattribute__(self, name)
Esempio n. 50
0
 def __getattr__(self, name):
     # Any gear buff we haven't assigned a value to, we don't have.
     if name in self.allowed_buffs:
         return False
     object.__getattribute__(self, name)
Esempio n. 51
0
 def __getattr__(self, key):
   if key in self:
     return self[key]
   else:
     return object.__getattribute__(self, key)
Esempio n. 52
0
 def __getattribute__(self, name):
     return object.__getattribute__(self, name)
Esempio n. 53
0
 def __getattribute__(self, name):
     if name in _StandaloneSSLConnection._OVERRIDDEN_ATTRIBUTES:
         return object.__getattribute__(self, name)
     return self._connection.__getattribute__(name)
Esempio n. 54
0
 def __getattribute__(self, name):
     return evernote_wait_try_again(
         getattr(object.__getattribute__(self, "_obj"), name))