Ejemplo n.º 1
    def equals(self, other):
        if other is None:
            return False

        # Hack here, we cannot just check the type here,
        # many types like Column is created dynamically,
        # so we check the class name and the sub classes.
        if (
            self.__class__.__name__ != other.__class__.__name__
            or inspect.getmro(type(self))[1:] != inspect.getmro(type(self))[1:]
            return False

        def cmp(x, y):
            if isinstance(x, Node):
                res = x.equals(y)
            elif isinstance(y, Node):
                res = y.equals(y)
            elif isinstance(x, (tuple, list)) and isinstance(y, (tuple, list)):
                res = all(map(cmp, x, y))
                res = x == y
            return res

        return all(map(cmp, self._slot_values(), other._slot_values()))
Ejemplo n.º 2
 def paste(self, obj, name = None, bForceOverwrite = False, pathkey = None, bHashById = False):
     types = inspect.getmro(type(obj))
     if BContainer in types:
         if bHashById == True:
             if PyLinXData.PyLinXDataObjects.PX_IdObject in types:                    
                 key = obj.ID
                 key = obj.get("Name")
             key = obj.get("Name")
         if name == None:
             # TODO: Error-Handling has to be implemented 
             print "Error BContainer.py: No key for paste-function!"
     if key in self.__Body.keys():
         if bForceOverwrite:
             self.__Body[key] = obj
             obj.__parent = self                
             If an object with corresponding Name exists, then an error message should be returned
             TODO: Has to be impemented
         self.__Body[key] = obj
         types = inspect.getmro(type(obj))
         if(BContainer in types):
             obj.__parent = self
Ejemplo n.º 3
def load_style_templates(styled_class, styled_attribute=None):
        Looks for a style template based on the styled_class and styled_attribute. The latter is optional. If no
        file exists for the combination, the code will search for the nonattributed style. If that fails, the code
        will continue the search with each ancestor of the styled_class, with and without attribute, until a match is
    :param styled_class: The class that represents the table being styled
    :param styled_attribute: Optional. The attribute being styled.
    for cls in getmro(styled_class):
        if styled_attribute:
            attributed_cartocss_file = FOOTPRINT_TEMPLATE_DIR + "/maps/%s__%s.cartocss" % (cls.__name__, styled_attribute)
            nonattributed_cartocss_file = attributed_cartocss_file.split('__')[0]+'.cartocss'
            attributed_cartocss_file = None
            nonattributed_cartocss_file = FOOTPRINT_TEMPLATE_DIR + "/maps/%s.cartocss" % cls.__name__

        for cartocss_file in map(lambda f: f, [attributed_cartocss_file, nonattributed_cartocss_file]):
            if os.path.exists(cartocss_file):
                cartocss_style_template = open(

                css_file = cartocss_file.replace('.cartocss', '.css')
                standardcss_style_template = open(
                    css_file, "r").read()
                return dict(cartocss=cartocss_style_template, css=standardcss_style_template)
    raise Exception("No style file found for style_class %s (nor its ancestors) %s %s without styled_attribute %s" %
                     ', '.join(map(lambda cls: cls.__name__, getmro(styled_class))),
                     'neither with nor' if styled_attribute else '',
                     styled_attribute or ''))
Ejemplo n.º 4
 def set(self,  attr, setObj, options = None):
     _type = type(self)
     if attr in _type._dictSetCallbacks:
         _type._dictSetCallbacks[attr](self,setObj, options)
     elif attr in self._dictSetCallbacks:
         self._dictSetCallbacks[attr](setObj, options)            
         if attr in _type._dictGetCallbacks:
             raise Exception(u"BContainer.set: Attribute " + attr + u" is write-protected! Please implement a set-method to write this \
             attribute or remove the get-method to remove write-protection!" )
         # None or empty string as attribute indicates complex set command with a whole dict to be set.
         elif attr == None or attr == u"": 
             types = inspect.getmro(type(setObj))
             if dict in types:
                 return self.__set_dict(setObj, options)
                 raise Exception("Error BContainer.set: No valid type for collective set. Use dict!")
         elif options == None: 
             self.__Attributes[attr] = setObj
             if attr == u"listPoints":
                 print self.__Attributes
         elif options == u"-p":
             val = self.get(attr)
             types = inspect.getmro(type(val))
             if (float in types) or (int in types):
                 self.set(attr,  val + setObj)
             elif tuple in types:
                 self.set(attr, tuple([a + b for a, b in zip(val, setObj ) ] ) )
             elif list in types:
                 self.set(attr, [a + b for a, b in zip(val, setObj ) ] )
Ejemplo n.º 5
	def analyze_param(self,param):
		self.temp_require_multipart = False
		if [list,tuple].count(type(param)):
			# Parameter seems to be an array
			if len(param)!=1:
				raise NeedToDefineParseTimeException("Only one element is allowed when defining ladon arrays")
			if type(param[0])!=type:
				raise NeedToDefineParseTimeException("Only types are allowed as list-element when defining an array")
			if inspect.getmro(param[0]).count(LadonType):
				if param[0]==attachment:
					self.temp_require_multipart = True

			self.has_lists = True
			if not self.type_order.count([param[0]]):
				self.type_order += [[param[0]]]
		elif type(param)==type:
			if inspect.getmro(param).count(LadonType):
				if param==attachment:
					self.temp_require_multipart = True
			raise NeedToDefineParseTimeException("Ladonized param definition must be a LadonType or iterable")
		return self.temp_require_multipart
Ejemplo n.º 6
 def process(self, event, parameter):
     """Process an event by calling the registered handler if there's one.
     method = self.handlers.get(event, None)
     if method:
         # if the method is a method of a class deriving from EventProcessor
         # we pass just parameter
         if (inspect.ismethod(method) and 
             (EventProcessor in inspect.getmro(method.im_class) or
              galry.InteractionManager in inspect.getmro(method.im_class))):
             fig = self.interaction_manager.figure
             # HACK: give access to paint_manager.set_data to the figure,
             # so that event processors can change the data
             # BAD SMELL HERE :(
             if not hasattr(fig, 'set_data'):
                 fig.set_data = self.parent.paint_manager.set_data
                 fig.copy_texture = self.parent.paint_manager.copy_texture
                 fig.set_rendering_options = self.parent.paint_manager.set_rendering_options
                 fig.get_processor = self.interaction_manager.get_processor
                 fig.get_visual = self.paint_manager.get_visual
                 fig.process_interaction = self.parent.process_interaction
             fig.resizeGL = self.parent.paint_manager.resizeGL
             # here, we are using the high level interface and figure
             # is the Figure object we pass to this function
             method(fig, parameter)
Ejemplo n.º 7
    def test_create_instance(self):
        tests the built-in get_instance() method
        app = self.engine.apps["test_app"]
        hook_expression = app.get_setting("test_hook_std")
        instance_1 = app.create_hook_instance(hook_expression)
        self.assertEqual(instance_1.second_method(another_dummy_param=True), True)
        instance_2 = app.create_hook_instance(hook_expression)
        self.assertNotEqual(instance_1, instance_2)

        # ensure if no base_class arg supplied we have Hook as the base class
        base_classes = inspect.getmro(instance_2.__class__)
        self.assertEqual(base_classes[-2], tank.Hook)
        self.assertEqual(base_classes[-1], object)

        # class to inject as a custom base class
        class Foobar(tank.Hook):

        # this hook has to be new style hook using `sgtk.get_hook_baseclass`
        test_hook_expression = "{config}/more_hooks/config_test_hook.py"

        # create an instance with an in injected base class
        instance_3 = app.create_hook_instance(test_hook_expression, base_class=Foobar)

        # get the resolution order of the base classes
        base_classes = inspect.getmro(instance_3.__class__)

        # ensure the last 3 classes in the order are Foobar, Hook, object
        self.assertEqual(base_classes[-3], Foobar)
        self.assertEqual(base_classes[-2], tank.Hook)
        self.assertEqual(base_classes[-1], object)
Ejemplo n.º 8
def get_class_that_defined_method(meth):
    Return the class that defines a method.

        meth (str): Class method.

        class: Class object, or None if not a class method.
    if sys.version_info >= (3, 0):
        # Written by @Yoel http://stackoverflow.com/a/25959545
        if inspect.ismethod(meth):
            for cls in inspect.getmro(meth.__self__.__class__):
               if cls.__dict__.get(meth.__name__) is meth:
                    return cls
            meth = meth.__func__ # fallback to __qualname__ parsing
        if inspect.isfunction(meth):
            cls = getattr(inspect.getmodule(meth),
                          meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
            if isinstance(cls, type):
                return cls
            # Writted by @Alex Martelli http://stackoverflow.com/a/961057
            for cls in inspect.getmro(meth.im_class):
                if meth.__name__ in cls.__dict__:
                    return cls
        except AttributeError:
            return None
    return None
Ejemplo n.º 9
 def __init__(self, lhs, rhs):
     self.lhs = lhs
     self.rhs = rhs 
     if types.IEvent in inspect.getmro(type(lhs)):
         event.subscribe(lhs, _(self).fire, self)
     if types.IEvent in inspect.getmro(type(rhs)):
         event.subscribe(rhs, _(self).fire, self)
Ejemplo n.º 10
def samegraph(A,B):
    "Returns true if the MRO's of A and B have an intersection."
    mro_A = sets.Set(inspect.getmro(A))
    mro_B = sets.Set(inspect.getmro(B))
    return bool(mro_A & mro_B)
Ejemplo n.º 11
def _GetClassImplementedInterfaces(class_):
    cache = __ImplementedInterfacesCache.GetSingleton()
    result = cache.GetResult(class_)
    if result is not None:
        return result

    result = set()

    mro = inspect.getmro(class_)

    for c in mro:
        interfaces = getattr(c, '__implements__', ())
        for interface in interfaces:
            interface_mro = inspect.getmro(interface)

            for interface_type in interface_mro:
                if interface_type in [Interface, object]:
                    # Ignore basic types

    result = frozenset(result)

    cache.SetResult(class_, result)
    return result
Ejemplo n.º 12
    def get_actions(cls):
        class_stack = inspect.getmro(cls)[::-1]

        cls.actions = cls.class_actions
        cls.actions_forms = {}
        cls.action_templates = {}

        for base_class in class_stack:
            check_classes = inspect.getmro(base_class)
            if base_class != cls and HttpAPIView in check_classes:
                if 'class_actions' in base_class.__dict__:
                    for action in base_class.class_actions:
                        if action not in cls.actions:
                if 'class_actions_forms' in base_class.__dict__:
                    for action in base_class.class_actions_forms:
                        cls.actions_forms[action] = base_class.class_actions_forms[action]
                if 'class_action_templates' in base_class.__dict__:
                    for action in base_class.class_action_templates:
                        cls.action_templates[action] = base_class.class_action_templates[action]
        if 'class_actions_forms' in cls.__dict__:
        if 'class_action_templates' in cls.__dict__:
        return cls.actions
Ejemplo n.º 13
def inheritdocstring(name, bases, attrs):
    Use as metaclass to inherit class and method docstrings from parent.
    Adapted from http://stackoverflow.com/questions/13937500/inherit-a-parent-class-docstring-as-doc-attribute
    Use this on classes defined in solver-specific interfaces to inherit docstrings from the high-level interface.
    if '__doc__' not in attrs or not attrs["__doc__"]:
        # create a temporary 'parent' to (greatly) simplify the MRO search
        temp = type('temporaryclass', bases, {})
        for cls in inspect.getmro(temp):
            if cls.__doc__ is not None:
                attrs['__doc__'] = cls.__doc__

    for attr_name, attr in attrs.items():
        if not attr.__doc__:
            for cls in inspect.getmro(temp):
                    if getattr(cls, attr_name).__doc__ is not None:
                        attr.__doc__ = getattr(cls, attr_name).__doc__
                except (AttributeError, TypeError):

    return type(name, bases, attrs)
 def test_question_pages_without_questions_are_filtered_out(self):
     # empty_page
     wizard = TestWizard.wizard_factory()()
     self.assertEqual(len(wizard.form_list), 2)
     self.assertIn(QuestionPageForm, inspect.getmro(wizard.form_list[0]))
     self.assertNotIn(TextPageForm, inspect.getmro(wizard.form_list[-1]))
Ejemplo n.º 15
def classname_from_method(method):
    Finds the requesting class of a method(bound or unbound)
    :param method: method to use
    :return: the class of the given method
        for cls in inspect.getmro(method.im_class):
            if method.__name__ in cls.__dict__:
                return cls.__name__
    except AttributeError:
            if inspect.ismethod(method):
                for cls in inspect.getmro(method.__self__.__class__):
                    if cls.__dict__.get(method.__name__) is method:
                        return cls.__name__
                method = method.__func__
            if inspect.isfunction(method):
                cls = getattr(inspect.getmodule(method),
                              method.__qualname__.split('.<locals>', 1)[0]
                              .rsplit('.', 1)[0])
                if isinstance(cls, type):
                    return cls.__name__
            return ''
        except AttributeError:
            return ''
Ejemplo n.º 16
 def __keyPressEvent_delete():
     #keys = self.activeGraphics.getChildKeys()
     objectsInFocus = list(self.activeGraphics.objectsInFocus)
     setDelete = set([])
     #for key in keys:
     for key in self.activeGraphics._BContainer__Body:    
         element = self.activeGraphics.getb(key)
         types = inspect.getmro(type(element))
         if (PyLinXDataObjects.PX_PlottableConnector in types):
             # deleting all connectors which are connected to an object, that is deleted
             elem0 = element.elem0
             if elem0 in objectsInFocus:
             elem1 = element.elem1
             if elem1 in objectsInFocus:
         # deleting all objects in focus
         if element in objectsInFocus:
     # removing the deleted connectors from the list of connected pins of the connected elements
     for _id in setDelete:
         element = self.activeGraphics.getb(_id)
         types = inspect.getmro(type(element))
         if PyLinXDataObjects.PX_PlottableConnector in types:
             idxInPin = element.idxInPin
             idxOutPin = element.idxOutPin
             elem0 = element.elem0
             elem1 = element.elem1
             #print "elem0: ", elem0
             #print "elem1: ", elem1
             setIdxConnectedOutPins = elem0.get("setIdxConnectedOutPins")
             setIdxConnectedInPins  = elem1.get("setIdxConnectedInPins")
             #print "setIdxConnectedOutPins: ", setIdxConnectedOutPins 
             #print "setIdxConnectedInPins: ", setIdxConnectedInPins
             #print "idxOutPin: ", idxOutPin
             #print "idxInPin: ", idxInPin
             if idxOutPin in setIdxConnectedOutPins: 
             if idxInPin in setIdxConnectedInPins: 
             #print "setIdxConnectedOutPins (1): ", setIdxConnectedOutPins 
             #print "setIdxConnectedInPins (1): ", setIdxConnectedInPins
             elem0.set("setIdxConnectedOutPins", setIdxConnectedOutPins)
             elem1.set("setIdxConnectedInPins", setIdxConnectedInPins)
     DataDictionary = self.rootContainer.getb("DataDictionary")
     bDictionary = (DataDictionary != None)
     for element in setDelete:
         if bDictionary:
             elementObject = self.activeGraphics.getb(element)
             name = elementObject.get("Name")
             if name in DataDictionary:
Ejemplo n.º 17
def common_bases(seq):
    iseq = iter(seq)
    bases = set(inspect.getmro(type(next(iseq))))
    for item in iseq:
        bases = bases.intersection(inspect.getmro(type(item)))
        if not bases:
    return bases
Ejemplo n.º 18
def ctype_struct_generator(module):
    module_structs = inspect.getmembers(module, predicate=(
        lambda x: (inspect.isclass(x) and ctypes.Structure in inspect.getmro(x))))

    # Sort by the line number in which the class appears
    module_structs.sort(key=lambda x: inspect.getsourcelines(x[1])[1])
    for name, obj in module_structs:
            if ctypes.Structure in inspect.getmro(obj) and hasattr(obj, '_fields_'):
                yield obj
Ejemplo n.º 19
Archivo: game.py Proyecto: wlaub/pybld
    def loadModules(self):
        Loads rooms from all modules in rooms/*.py. and sets
        inventory to the room named 'inv', which must exist.
        with open("logs/gameload", "w") as f:
            roomFiles = os.listdir('./rooms')
            items = []
            combos = []
            for name in roomFiles:
                modName, modExt = os.path.splitext(name)
                if modExt == '.py' and modName != '__init__':
                    f.write("loading module {}\n".format(name))
                    mod = importlib.import_module("rooms."+modName)

                    for val in dir(mod):
                            thing = mod.__dict__[val]
                            if Room in inspect.getmro(thing):
                                f.write("Found Room\n")
                            if Item in inspect.getmro(thing):
                                f.write("Found item\n")
                                    nItem = thing()
                                except Exception as e:
                            elif Combo in inspect.getmro(thing):
                                    nCombo = thing()
                                except Exception as e:
                        except Exception as e:

            for item in items:
                room = self.rooms[item.loc]
                room.items[item.name] = item
                item.room = room
                f.write("Adding item {} to room {}\n".format(item.name, room.name))

            for combo in combos:
                room = self.rooms[combo.loc]
                room.combos[combo.name] = combo
                combo.room = room
                f.write("Adding combo {} to room {}\n".format(combo.name, room.name))

            self.inv = self.rooms['inv']

            for name, desc, qty in achieve.achievements:
                self.achievements[name] = Achievement(desc, qty)
Ejemplo n.º 20
 def receiveMessage(self, message, sender):
     for each in inspect.getmro(message.__class__):
         methodName = 'receiveMsg_%s'%each.__name__
         if hasattr(self, methodName):
             for klasses in inspect.getmro(self.__class__):
                 if hasattr(klasses, methodName):
                     if getattr(klasses, methodName)(self, message, sender) != self.SUPER:
     if hasattr(self, 'receiveUnrecognizedMessage'):
         self.receiveUnrecognizedMessage(message, sender)
Ejemplo n.º 21
def test_inheritance():
    """Test that inheritance is preserved from object"""
    assert object in getmro(BaseEventEmitter)

    class example(BaseEventEmitter):
        def __init__(self):
            super(example, self).__init__()

    assert BaseEventEmitter in getmro(example)
    assert object in getmro(example)
Ejemplo n.º 22
 def __init__(self, cond, ifpart, elsepart):
     self.cond = cond
     self.ifpart = ifpart
     self.elsepart = elsepart
     if types.IEvent in inspect.getmro(type(cond)):
         event.subscribe(cond, _(self).fire, self)
     if types.IEvent in inspect.getmro(type(ifpart)):
         event.subscribe(ifpart, _(self).fire, self)
     if types.IEvent in inspect.getmro(type(elsepart)):
         event.subscribe(elsepart, _(self).fire, self)
Ejemplo n.º 23
def get_adapter_path(obj, to_cls):
    Returns the adapter path that would be used to adapt `obj` to `to_cls`.
    from_cls = type(obj)
    key = (from_cls, to_cls)
    if key not in __mro__:
        __mro__[key] = list(itertools.product(inspect.getmro(from_cls), inspect.getmro(to_cls)))

    return __mro__[key]
Ejemplo n.º 24
    def SmartSet(self, obj, attr_name, new_attr):
        """Replace obj.attr_name with new_attr.

        This method is smart and works at the module, class, and instance level
        while preserving proper inheritance. It will not stub out C types
        however unless that has been explicitly allowed by the type.

        This method supports the case where attr_name is a staticmethod or a
        classmethod of obj.

          - If obj is an instance, then it is its class that will actually be
            stubbed. Note that the method Set() does not do that: if obj is
            an instance, it (and not its class) will be stubbed.
          - The stubbing is using the builtin getattr and setattr. So, the
            __get__ and __set__ will be called when stubbing (TODO: A better
            idea would probably be to manipulate obj.__dict__ instead of
            getattr() and setattr()).

        Raises AttributeError if the attribute cannot be found.
        if (inspect.ismodule(obj) or
                (not inspect.isclass(obj) and attr_name in obj.__dict__)):
            orig_obj = obj
            orig_attr = getattr(obj, attr_name)

            if not inspect.isclass(obj):
                mro = list(inspect.getmro(obj.__class__))
                mro = list(inspect.getmro(obj))


            orig_attr = None

            for cls in mro:
                    orig_obj = cls
                    orig_attr = getattr(obj, attr_name)
                except AttributeError:

        if orig_attr is None:
            raise AttributeError("Attribute not found.")

        # Calling getattr() on a staticmethod transforms it to a 'normal'
        # function. We need to ensure that we put it back as a staticmethod.
        old_attribute = obj.__dict__.get(attr_name)
        if (old_attribute is not None and
                isinstance(old_attribute, staticmethod)):
            orig_attr = staticmethod(orig_attr)

        self.stubs.append((orig_obj, attr_name, orig_attr))
        setattr(orig_obj, attr_name, new_attr)
Ejemplo n.º 25
def commonbase(cls1, cls2):   # XXX single inheritance only  XXX hum
    l1 = inspect.getmro(cls1)
    l2 = inspect.getmro(cls2) 
    if l1[-1] != object: 
        l1 = l1 + (object,) 
    if l2[-1] != object: 
        l2 = l2 + (object,) 
    for x in l1: 
        if x in l2: 
            return x 
    assert 0, "couldn't get to commonbase of %r and %r" % (cls1, cls2)
Ejemplo n.º 26
def get_attrs(node):
    from .core import Node

    tp = type(node) if not inspect.isclass(node) else node

    if inspect.getmro(tp) is None:
        tp = type(tp)

    return tuple(compat.OrderedDict.fromkeys(
        it for it in
        itertools.chain(*(cls.__slots__ for cls in inspect.getmro(tp) if issubclass(cls, Node)))
        if not it.startswith('__')))
Ejemplo n.º 27
def create_representation(layer_name,db,rep):
    mod = __import__('layers.'+layer_name)
    for name, obj in inspect.getmembers(mod):
        for name2,obj2 in inspect.getmembers(obj):
            if inspect.isclass(obj2) and \
               name2 == layer_name and \
               RepresentationLayer in inspect.getmro(obj2) and \
               len(inspect.getmro(obj2)) > 1:
                    layer = obj2(name2)
                    return layer
    return None
Ejemplo n.º 28
    def get_like_type_score(self, related):

        :rtype: decimal.Decimal.
        s_tree  = inspect.getmro(self.content_type.model_class())
        r_tree  = inspect.getmro(related.content_type.model_class())
        shared  = len(set(s_tree) & set(r_tree))
        total   = len(set(s_tree + r_tree))

        return decimal.Decimal(
            (float(shared) / float(total)) * LIKE_TYPE_FACTOR
Ejemplo n.º 29
def _registered_kl(type_a, type_b):
  """Get the KL function registered for classes a and b."""
  hierarchy_a = inspect.getmro(type_a)
  hierarchy_b = inspect.getmro(type_b)
  dist_to_children = None
  kl_fn = None
  for mro_to_a, parent_a in enumerate(hierarchy_a):
    for mro_to_b, parent_b in enumerate(hierarchy_b):
      candidate_dist = mro_to_a + mro_to_b
      candidate_kl_fn = _DIVERGENCES.get((parent_a, parent_b), None)
      if not kl_fn or (candidate_kl_fn and candidate_dist < dist_to_children):
        dist_to_children = candidate_dist
        kl_fn = candidate_kl_fn
  return kl_fn
Ejemplo n.º 30
def isInstanceOf(obj,objType):
  """?? Is the object an instance (or derived from) of the class objType?"""

  # Allow a list or tuple of objects to be passed
  if iterable(objType):
    if type(obj) is InstanceType:
      mro = inspect.getmro(obj.__class__)
      for ot in objType:
        if ot in mro: return True

  # If its not iterable do it in one line
  if type(obj) is InstanceType and objType in inspect.getmro(obj.__class__): return True

  return False