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) else: 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) else: 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 ) ] )
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__ break for attr_name, attr in attrs.items(): if not attr.__doc__: for cls in inspect.getmro(temp): try: if getattr(cls, attr_name).__doc__ is not None: attr.__doc__ = getattr(cls, attr_name).__doc__ break except (AttributeError, TypeError): continue return type(name, bases, attrs)
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 found. :param styled_class: The class that represents the table being styled :param styled_attribute: Optional. The attribute being styled. :return: """ 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' else: 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( cartocss_file, "r").read() 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" % (styled_class.__name__, ', '.join(map(lambda cls: cls.__name__, getmro(styled_class))), 'neither with nor' if styled_attribute else '', styled_attribute or ''))
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): pass # 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)
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 continue result.add(interface_type) result = frozenset(result) cache.SetResult(class_, result) return result
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_A.discard(object) mro_B = sets.Set(inspect.getmro(B)) mro_B.discard(object) return bool(mro_A & mro_B)
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)) else: res = x == y return res return all(map(cmp, self._slot_values(), other._slot_values()))
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): self.analyze_class(param[0]) else: self.add_primitive_type(param[0]) 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): self.analyze_class(param) else: self.add_primitive_type(param) if param==attachment: self.temp_require_multipart = True else: raise NeedToDefineParseTimeException("Ladonized param definition must be a LadonType or iterable") return self.temp_require_multipart
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)
def get_class_that_defined_method(meth): """ Return the class that defines a method. Arguments: meth (str): Class method. Returns: 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 else: try: # 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
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: cls.actions.append(action) 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__: cls.actions_forms.update(cls.class_actions_forms) if 'class_action_templates' in cls.__dict__: cls.action_templates.update(cls.class_action_templates) return cls.actions
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 else: key = obj.get("Name") else: key = obj.get("Name") else: if name == None: # TODO: Error-Handling has to be implemented print "Error BContainer.py: No key for paste-function!" return if key in self.__Body.keys(): if bForceOverwrite: self.__Body[key] = obj obj.__parent = self else: ''' If an object with corresponding Name exists, then an error message should be returned TODO: Has to be impemented ''' pass else: self.__Body[key] = obj types = inspect.getmro(type(obj)) if(BContainer in types): obj.__parent = self
def test_question_pages_without_questions_are_filtered_out(self): # empty_page QuestionPage.objects.create() 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]))
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 """ try: for cls in inspect.getmro(method.im_class): if method.__name__ in cls.__dict__: return cls.__name__ except AttributeError: try: 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 ''
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))): method(parameter) else: 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)
def common_bases(seq): """http://stackoverflow.com/questions/13252333/python-check-if-all-elements-of-a-list-are-the-same-type""" iseq = iter(seq) bases = set(inspect.getmro(type(next(iseq)))) for item in iseq: bases = bases.intersection(inspect.getmro(type(item))) if not bases: break return bases
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
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: setDelete.add(element.ID) elem1 = element.elem1 if elem1 in objectsInFocus: setDelete.add(element.ID) # deleting all objects in focus if element in objectsInFocus: setDelete.add(element.ID) # 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: setIdxConnectedOutPins.remove(idxOutPin) if idxInPin in setIdxConnectedInPins: setIdxConnectedInPins.remove(idxInPin) #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: DataDictionary.pop(name) self.activeGraphics.delete(element) self.repaint()
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): try: thing = mod.__dict__[val] if Room in inspect.getmro(thing): f.write("Found Room\n") self._addRoom(thing()) if Item in inspect.getmro(thing): f.write("Found item\n") try: nItem = thing() items.append(nItem) self._addItem(nItem) except Exception as e: f.write(str(e)+'\n') elif Combo in inspect.getmro(thing): try: nCombo = thing() combos.append(nCombo) except Exception as e: f.write(str(e)+'\n') except Exception as e: pass 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)
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: return if hasattr(self, 'receiveUnrecognizedMessage'): self.receiveUnrecognizedMessage(message, sender)
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]
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)
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)
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. Notes: - 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) else: if not inspect.isclass(obj): mro = list(inspect.getmro(obj.__class__)) else: mro = list(inspect.getmro(obj)) mro.reverse() orig_attr = None for cls in mro: try: orig_obj = cls orig_attr = getattr(obj, attr_name) except AttributeError: continue 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)
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)
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) layer.create(db,rep) return layer return None
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('__')))
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 )
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
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
def convert(self, model, mapper, prop, field_args, db_session=None): if not hasattr(prop, 'columns') and not hasattr(prop, 'direction'): return elif not hasattr(prop, 'direction') and len(prop.columns) != 1: raise TypeError('Do not know how to convert multiple-column ' + 'properties currently') kwargs = { 'validators': [], 'filters': [], 'default': None, } converter = None column = None types = None if not hasattr(prop, 'direction'): column = prop.columns[0] # Support sqlalchemy.schema.ColumnDefault, so users can benefit # from setting defaults for fields, e.g.: # field = Column(DateTimeField, default=datetime.utcnow) default = getattr(column, 'default', None) if default is not None: # Only actually change default if it has an attribute named # 'arg' that's callable. callable_default = getattr(default, 'arg', None) if callable_default is not None: # ColumnDefault(val).arg can be also a plain value default = callable_default(None) if callable( callable_default) else callable_default kwargs['default'] = default if column.nullable: kwargs['validators'].append(validators.Optional()) else: kwargs['validators'].append(validators.Required()) if db_session and column.unique: kwargs['validators'].append( Unique(lambda: db_session, model, column)) if self.use_mro: types = inspect.getmro(type(column.type)) else: types = [type(column.type)] for col_type in types: type_string = '%s.%s' % (col_type.__module__, col_type.__name__) if type_string.startswith('sqlalchemy'): type_string = type_string[11:] if type_string in self.converters: converter = self.converters[type_string] break else: for col_type in types: if col_type.__name__ in self.converters: converter = self.converters[col_type.__name__] break else: raise ModelConversionError( 'Could not find field converter for %s (%r).' % (prop.key, types[0])) else: # We have a property with a direction. if not db_session: raise ModelConversionError( "Cannot convert field %s, need DB session." % prop.key) foreign_model = prop.mapper.class_ nullable = True for pair in prop.local_remote_pairs: if not pair[0].nullable: nullable = False kwargs.update({ 'allow_blank': nullable, 'query_factory': lambda: db_session.query(foreign_model).all() }) converter = self.converters[prop.direction.name] if field_args: kwargs.update(field_args) return converter(model=model, mapper=mapper, prop=prop, column=column, field_args=kwargs)
def __init__(cls, name, bases, dct): super(MPITestCaseMeta, cls).__init__(name, bases, dct) parent = getmro(cls)[1] for n, obj in parent.__dict__.items(): if n.startswith('assert') or n == 'fail': setattr(cls, 'collective_' + n, mpi_fail_if_any(obj))
def __init__(self, exc_value=None, exc_type=None, exc_tb=None, captureVars=False): """ Initialize me with an explanation of the error. By default, this will use the current C{exception} (L{sys.exc_info}()). However, if you want to specify a particular kind of failure, you can pass an exception as an argument. If no C{exc_value} is passed, then an "original" C{Failure} will be searched for. If the current exception handler that this C{Failure} is being constructed in is handling an exception raised by L{raiseException}, then this C{Failure} will act like the original C{Failure}. For C{exc_tb} only L{traceback} instances or L{None} are allowed. If L{None} is supplied for C{exc_value}, the value of C{exc_tb} is ignored, otherwise if C{exc_tb} is L{None}, it will be found from execution context (ie, L{sys.exc_info}). @param captureVars: if set, capture locals and globals of stack frames. This is pretty slow, and makes no difference unless you are going to use L{printDetailedTraceback}. """ global count count = count + 1 self.count = count self.type = self.value = tb = None self.captureVars = captureVars if isinstance(exc_value, str) and exc_type is None: raise TypeError("Strings are not supported by Failure") stackOffset = 0 if exc_value is None: exc_value = self._findFailure() if exc_value is None: self.type, self.value, tb = sys.exc_info() if self.type is None: raise NoCurrentExceptionError() stackOffset = 1 elif exc_type is None: if isinstance(exc_value, Exception): self.type = exc_value.__class__ else: #allow arbitrary objects. self.type = type(exc_value) self.value = exc_value else: self.type = exc_type self.value = exc_value if isinstance(self.value, Failure): self.__dict__ = self.value.__dict__ return if tb is None: if exc_tb: tb = exc_tb elif _PY3: tb = self.value.__traceback__ frames = self.frames = [] stack = self.stack = [] # added 2003-06-23 by Chris Armstrong. Yes, I actually have a # use case where I need this traceback object, and I've made # sure that it'll be cleaned up. self.tb = tb if tb: f = tb.tb_frame elif not isinstance(self.value, Failure): # we don't do frame introspection since it's expensive, # and if we were passed a plain exception with no # traceback, it's not useful anyway f = stackOffset = None while stackOffset and f: # This excludes this Failure.__init__ frame from the # stack, leaving it to start with our caller instead. f = f.f_back stackOffset -= 1 # Keeps the *full* stack. Formerly in spread.pb.print_excFullStack: # # The need for this function arises from the fact that several # PB classes have the peculiar habit of discarding exceptions # with bareword "except:"s. This premature exception # catching means tracebacks generated here don't tend to show # what called upon the PB object. while f: if captureVars: localz = f.f_locals.copy() if f.f_locals is f.f_globals: globalz = {} else: globalz = f.f_globals.copy() for d in globalz, localz: if "__builtins__" in d: del d["__builtins__"] localz = localz.items() globalz = globalz.items() else: localz = globalz = () stack.insert(0, ( f.f_code.co_name, f.f_code.co_filename, f.f_lineno, localz, globalz, )) f = f.f_back while tb is not None: f = tb.tb_frame if captureVars: localz = f.f_locals.copy() if f.f_locals is f.f_globals: globalz = {} else: globalz = f.f_globals.copy() for d in globalz, localz: if "__builtins__" in d: del d["__builtins__"] localz = list(localz.items()) globalz = list(globalz.items()) else: localz = globalz = () frames.append(( f.f_code.co_name, f.f_code.co_filename, tb.tb_lineno, localz, globalz, )) tb = tb.tb_next if inspect.isclass(self.type) and issubclass(self.type, Exception): parentCs = getmro(self.type) self.parents = list(map(reflect.qual, parentCs)) else: self.parents = [self.type]
def find_subclasses_in_module(module, base_cls): """Finds subclasses of given class in the module.""" name_values = inspect.getmembers( module, lambda x: inspect.isclass(x) and not inspect.isabstract(x) and (base_cls in inspect.getmro(x))) return [v for _, v in name_values]
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. Notes: - 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()). Args: obj: The object whose attributes we want to modify. attr_name: The name of the attribute to modify. new_attr: The new value for the attribute. 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) else: if not inspect.isclass(obj): mro = list(inspect.getmro(obj.__class__)) else: mro = list(inspect.getmro(obj)) mro.reverse() orig_attr = None found_attr = False for cls in mro: try: orig_obj = cls orig_attr = getattr(obj, attr_name) found_attr = True except AttributeError: continue if not found_attr: 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)
def names_and_fields(self, _fields_, superclass, anonymous_fields=None): # _fields_: list of (name, ctype, [optional_bitfield]) if isinstance(_fields_, tuple): _fields_ = list(_fields_) for f in _fields_: tp = f[1] if not isinstance(tp, _CDataMeta): raise TypeError("Expected CData subclass, got %s" % (tp, )) if isinstance(tp, StructOrUnionMeta): tp._make_final() if len(f) == 3: if (not hasattr(tp, '_type_') or not isinstance(tp._type_, str) or tp._type_ not in "iIhHbBlLqQ"): #XXX: are those all types? # we just dont get the type name # in the interp level thrown TypeError # from rawffi if there are more raise TypeError('bit fields not allowed for type ' + tp.__name__) all_fields = [] for cls in reversed(inspect.getmro(superclass)): # The first field comes from the most base class all_fields.extend(getattr(cls, '_fields_', [])) all_fields.extend(_fields_) names = [f[0] for f in all_fields] rawfields = [] for f in all_fields: if len(f) > 2: rawfields.append((f[0], f[1]._ffishape_, f[2])) else: rawfields.append((f[0], f[1]._ffishape_)) # hack for duplicate field names already_seen = set() names1 = names names = [] for f in names1: if f not in already_seen: names.append(f) already_seen.add(f) already_seen = set() for i in reversed(range(len(rawfields))): if rawfields[i][0] in already_seen: rawfields[i] = (('$DUP%d$%s' % (i, rawfields[i][0]), ) + rawfields[i][1:]) already_seen.add(rawfields[i][0]) # /hack _set_shape(self, rawfields, self._is_union) fields = {} for i, field in enumerate(all_fields): name = field[0] value = field[1] is_bitfield = (len(field) == 3) fields[name] = Field(name, self._ffistruct_.fieldoffset(name), self._ffistruct_.fieldsize(name), value, i, is_bitfield) if anonymous_fields: resnames = [] for i, field in enumerate(all_fields): name = field[0] value = field[1] is_bitfield = (len(field) == 3) startpos = self._ffistruct_.fieldoffset(name) if name in anonymous_fields: for subname in value._names_: resnames.append(subname) subfield = getattr(value, subname) relpos = startpos + subfield.offset subvalue = subfield.ctype fields[subname] = Field(subname, relpos, subvalue._sizeofinstances(), subvalue, i, is_bitfield, inside_anon_field=fields[name]) else: resnames.append(name) names = resnames self._names_ = names for name, field in fields.items(): setattr(self, name, field)
def _stop_buggy_background_worker_qthreads(widget): """ There is a bug in the worker/threading code in the BrowserWidget that was fixed in v0.1.17 and the tk-multi-workfiles Save As dialog that was fixed in v0.3.22. The bug results in a fatal crash if the BrowserWidget is cleaned up properly or if the Save As dialog is closed before the thread has completely stopped! However, because the engine was previously not releasing any dialogs, the cleanup code was never running which meant the bug was hidden! Now the engine has been fixed so that it cleans up correctly, all old versions of Multi Publish and apps using a pre-v0.1.17 version of the BrowserWidget became extremely unstable. As a workaround, this function finds all pre-v0.1.17 BrowserWidgets and pre-v0.3.22 SaveAsForms and applies a fix (basically waits for the worker thread to stop) to avoid instability! """ checked_classes = {} widgets = [widget] for w in widgets: # look through class hierarchy - can't use isinstance here # because we don't know which module the BrowserWidget would # be from! cls_type = None for cls in inspect.getmro(type(w)): # stop if we've previously checked this class: cls_type = checked_classes.get(cls, None) if cls_type != None: break checked_classes[cls] = "" # only care about certain specific classes: if cls.__name__ == "BrowserWidget": # tk-framework-widget.BrowserWidget # check the class has some members we know about and that # have been there since the first version of the code: if (hasattr(w, "_worker") and isinstance(w._worker, QtCore.QThread) and hasattr(w, "_app") and isinstance(w._app, application.Application) and hasattr(w, "_spin_icons") and isinstance(w._spin_icons, list)): # assume that this is derived from an actual tk-framework-widget.BrowserWidget! cls_type = "BrowserWidget" elif cls.__name__ == "SaveAsForm": # tk-multi-workfiles.SaveAsForm # check the class has some members we know about and that # have been there since the first version of the code: if (hasattr(w, "_preview_updater") and isinstance(w._preview_updater, QtCore.QThread) and hasattr(w, "_reset_version") and isinstance(w._reset_version, bool)): # assume that this is derived from an actual tk-multi-workfiles.SaveAsForm! cls_type = "SaveAsForm" if cls_type != None: checked_classes[cls] = cls_type break if cls_type: worker = None if cls_type == "BrowserWidget": worker = w._worker elif cls_type == "SaveAsForm": worker = w._preview_updater else: continue # now check to see if the worker already contains the fix: if hasattr(worker, "_SGTK_IMPLEMENTS_QTHREAD_CRASH_FIX_"): # this is already fixed so we don't need to do anything more! continue # lets make sure the worker is stopped... worker.stop() # and wait for the thread to finish - this line is the fix! worker.wait() else: # add all child widgets to list to be checked widgets.extend(w.children()) continue
def sympify(a, locals=None, convert_xor=True, strict=False, rational=False): """ Converts an arbitrary expression to a type that can be used inside sympy. For example, it will convert python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE. It currently accepts as arguments: - any object defined in sympy (except matrices [TODO]) - standard numeric python types: int, long, float, Decimal - strings (like "0.09" or "2e-19") - booleans, including ``None`` (will leave them unchanged) - lists, sets or tuples containing any of the above If the argument is already a type that sympy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type. >>> from sympy import sympify >>> sympify(2).is_integer True >>> sympify(2).is_real True >>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e-45").is_real True If the expression could not be converted, a SympifyError is raised. >>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse u'x***2'" If the option ``strict`` is set to ``True``, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised. >>> sympify(True) True >>> sympify(True, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: True To extend `sympify` to convert custom objects (not derived from `Basic`), the static dictionary `convert` is provided. The custom converters are usually added at import time, and will apply to all objects of the given class or its derived classes. For example, all geometry objects derive from `GeometryEntity` class, and should not be altered by the converter, so we add the following after defining that class: >>> from sympy.core.sympify import converter >>> from sympy.geometry.entity import GeometryEntity >>> converter[GeometryEntity] = lambda x: x """ from containers import Tuple try: cls = a.__class__ except AttributeError: #a is probably an old-style class object cls = type(a) if cls in sympy_classes: return a if cls in (bool, type(None)): if strict: raise SympifyError(a) else: return a try: return converter[cls](a) except KeyError: for superclass in getmro(cls): try: return converter[superclass](a) except KeyError: continue try: return a._sympy_() except AttributeError: pass if not isinstance(a, basestring): for coerce in (float, int): try: return sympify(coerce(a)) except (TypeError, ValueError, AttributeError, SympifyError): continue if strict: raise SympifyError(a) if isinstance(a, tuple): return Tuple(*[sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a]) if iterable(a): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a]) except TypeError: # Not all iterables are rebuildable with their type. pass # At this point we were given an arbitrary expression # which does not inherit from Basic and doesn't implement # _sympy_ (which is a canonical and robust way to convert # anything to SymPy expression). # # As a last chance, we try to take "a"'s normal form via unicode() # and try to parse it. If it fails, then we have no luck and # return an exception try: a = unicode(a) except Exception, exc: raise SympifyError(a, exc)
s.save() fdsfds with open_book("../gnucash_books/default_book.gnucash") as s: # accessing the book object from the session book = s.book # accessing root accounts root = book.root_account # accessing children accounts of root r = s.book.root_account.children(name="Assets").children[0] for acc in s.book.root_account.children(name="Assets").children[0].children: print(acc) print(inspect.getmro(Budget)) print(inspect.getmro(Recurrence)) b = Budget(name=lambda x: x, foo="3") b = Budget(name=lambda x: x, foo="3") fdsd print(b) fdsfds with create_book() as s: # retrieve list of slots print(s.book.slots) # set slots s.book["myintkey"] = 3 s.book["mystrkey"] = "hello" s.book["myboolkey"] = True
def is_pure_dataclass(value): if not dataclasses_support or not inspect.isclass(value): return False dataclasses = import_dataclasses('is_pure_dataclass') classes = [c for c in inspect.getmro(value) if c != object] return all(dataclasses.is_dataclass(c) for c in classes)
# in other programming language, we are ChildClass extends ParentClass # in python, we write ChildClass(ParentClass): which means the same thing # python supports inheriting multiple classes, ChildClass(ParentOneClass, ParentTwoClass): # in python every class, custom or user-defined, inherits `object` class # but in python 3, we do not have to use `MyClass(object):`, python interprets `MyClass:` as the same # we can view the inheritance tree by inspecting method resolution order or MRO (discussed later) # A boolean value is an instance of `bool` class which inherits `int` class which inherits `object` class # we can use `__class__` property of an object to see its constructor class boolVal = True # in case of multiple inheritance, `__bases__` return all inherited classes while `__base__` returns first inherit class print('boolVal.__class__.__bases__ => ', boolVal.__class__.__bases__) # we can use `getmro` function from `insepct` package to see MRO print('getmro(boolVal.__class__) => ', getmro(boolVal.__class__)) # When a child class inherits parent class, child class has access to all properties and methods of parent class. # When we try to access an attribute on an instance of child class, it first searches for instance attribute, then class attribute on it, then class attribute on parent class, then class attributes on the classes they inherit # single inheritance class AGrandParentOne: classAttrA = 'AGrandParentOneClassAttrA' classAttrB = 'AGrandParentOneClassAttrB' classAttrC = 'AGrandParentOneClassAttrC' class AParentOne(AGrandParentOne): classAttrA = 'AParentOneClassAttrA'
def export_capacities(self): """ List Mimetypes that current object can export to """ return [export for cls in getmro(type(self)) if hasattr(cls, "EXPORT_TO") for export in cls.EXPORT_TO]
for method in inspect.getmembers(q, predicate=inspect.ismethod): # print(type(method[1])) print(method[0]) print() print('Invoke:') class_name = "Quadrilateral" method = "get_area" obj = globals()[class_name](a=3, b=4, c=3, d=4, diagonal=5) answer = getattr(obj, method)() print(answer) print('Superclass:') # print(super(q.__class__)) print(inspect.getmro(Quadrilateral)[1]) print('-----------------------------------------') # # def myfunc(): # felf = globals()[inspect.getframeinfo(inspect.currentframe()).function] # print("** myfunc inspect : %s"%felf.__name__) # # felf = globals()[sys._getframe().f_code.co_name] # print("** myfunc globals : %s"%felf.__name__) # # print( 'wrapper =' ) # print( myfunc ) # # print( 'done myfunc' )
import inspect print "The class hierarchy for built-in exceptions is:" inspect.getclasstree(inspect.getmro(BaseException)) def classtree(cls, indent=0): print '.' * indent, cls.__name__ for subcls in cls.__subclasses__(): classtree(subcls, indent + 3) classtree(BaseException)
def __init__(self, grid, Youngs_modulus=6.5e11, Poissons_ratio=0.25, rho_mantle=3300., rho_fill=0., elastic_thickness=35000., BC_W='0Displacement0Slope', BC_E='0Displacement0Slope', BC_N='0Displacement0Slope', BC_S='0Displacement0Slope', g=9.81, **kwds): """Constructor for Wickert's gFlex in Landlab.""" assert RasterModelGrid in inspect.getmro(grid.__class__) if NO_GFLEX: raise ImportError( "gFlex not installed! For installation instructions see " + "gFlex on GitHub: https://github.com/awickert/gFlex") BC_options = ('0Displacement0Slope', '0Moment0Shear', '0Slope0Shear', 'Periodic') # instantiate the module: self.flex = gflex.F2D() flex = self.flex # set up the grid variables: self._grid = grid flex.dx = grid.dx flex.dy = grid.dy # we assume these properties are fixed in this relatively # straightforward implementation, but they can still be set if you # want: try: flex.Method = kwds['Method'] except KeyError: flex.Method = 'FD' try: flex.PlateSolutionType = kwds['PlateSolutionType'] except KeyError: flex.PlateSolutionType = 'vWC1994' try: flex.Solver = kwds['Solver'] except KeyError: flex.Solver = 'direct' try: quiet = kwds['Quiet'] except KeyError: flex.Quiet = True else: flex.Quiet = bool(quiet) flex.E = float(Youngs_modulus) flex.nu = float(Poissons_ratio) flex.rho_m = float(rho_mantle) flex.rho_fill = float(rho_fill) flex.g = float(g) flex.BC_W = BC_W flex.BC_E = BC_E flex.BC_S = BC_S flex.BC_N = BC_N for i in (flex.BC_E, flex.BC_W, flex.BC_N, flex.BC_S): assert i in BC_options if BC_W == 'Periodic': assert BC_E == 'Periodic' if BC_E == 'Periodic': assert BC_W == 'Periodic' if BC_N == 'Periodic': assert BC_S == 'Periodic' if BC_S == 'Periodic': assert BC_N == 'Periodic' Te_in = elastic_thickness try: flex.Te = float(Te_in) except ValueError: try: flex.Te = grid.at_node[Te_in].view().reshape(grid.shape) except TypeError: flex.Te = Te_in.view().reshape(grid.shape) self._input_var_names.add(Te_in) self._output_var_names.add(Te_in) # set up the link between surface load stresses in the gFlex component # and the LL grid field: flex.qs = grid.at_node['surface_load__stress'].view().reshape( grid.shape) # create a holder for the "pre-flexure" state of the grid, to allow # updating of elevs: self.pre_flex = np.zeros(grid.number_of_nodes, dtype=float) # create the primary output field: self.grid.add_zeros('lithosphere_surface__elevation_increment', at='node', dtype=float, noclobber=False)
def getParserTags(cls): tags = {} for cls in reversed(getmro(cls)): if hasattr(cls, "PARSER_TAGS"): tags.update(cls.PARSER_TAGS) return tags