我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用types.DictionaryType()。
def get_value(my, path): parts = path.split("/") current = my.package for part in parts: current = current.get(part) # explict None comparison: empty string should go through if current == None: raise HandlerException("Part [%s] does not exist in package" % part) # if this is still a dictionary and it has __VALUE__ in it, the # get that value if type(current) == types.DictionaryType and current.has_key("__VALUE__"): current = current.get("__VALUE__") if type(current) == types.ListType: return current[0] else: return current
def _json_object_to_object(self, json_object, entity_class, context={}): if type(json_object) == types.DictionaryType: if hasattr(entity_class, '_is_paginated') and entity_class._is_paginated: try: if hasattr(self, '_process_page'): return self._process_page(json_object, entity_class, context) else: raise AttributeError('Class %s does not have _process_page() method' % entity_class.__name__) except ValueError: return map_to_object(json_object, entity_class) else: return map_to_object(json_object, entity_class) elif type(json_object) == types.ListType: objects = [] for obj in json_object: objects.append(map_to_object(obj, entity_class)) # if auto_page is set, return a page with the items if 'typeId' in json_object and json_object['typeId'] == 'com.tintri.api.rest.v310.dto.Page' and self.__auto_page: return TintriPage(paginated=entity_class._is_paginated, items=objects, context=context) else: return objects else: return json_object # Return any other type as is, such as None, string, number, boolean
def _datatype(self): datatype = self['datatype'] if type(datatype) is types.DictionaryType: self._counterArgs = datatype.copy() if self._counterArgs.has_key('counter'): datatype = self._counterArgs['counter'] del self._counterArgs['counter'] else: datatype = 'numeric' else: self._counterArgs = {} if _counterCommands.has_key(datatype): self._counterCommand = _counterCommands[datatype] elif callable(datatype): self._counterCommand = datatype else: validValues = _counterCommands.keys() validValues.sort() raise ValueError, ('bad datatype value "%s": must be a' + ' function or one of %s') % (datatype, validValues)
def iterate(self): self.check_file() self.handler.start() dirpath, filename = os.path.split(self.filename) modulename = filename[:-3] if dirpath in sys.path: sys.path.remove(dirpath) sys.path.insert(0, dirpath) module = __import__(modulename) member_names = dir(module) for name in member_names: attr = getattr(module, name) if isinstance(attr, Template): self.handler.handle(attr) elif isinstance(attr, types.ListType): for mem in attr: if isinstance(attr, Template): self.handler.handle(attr) elif isinstance(attr, types.DictionaryType): for k in attr: if isinstance(attr, Template): self.handler.handle(attr[k])
def process_message(self, topic, payload, *args): log.debug('Bus receive: topic={topic}, payload={payload}', topic=topic, payload=payload) # TODO: filter by realm/topic # decode message if type(payload) is types.DictionaryType: message = payload.copy() elif type(payload) is types.ListType: message = OrderedDict(payload) else: raise TypeError('Unable to handle data type "{}" from bus'.format(type(payload))) # compute storage location from topic and message storage_location = self.storage_location(message) log.debug('Storage location: {storage_location}', storage_location=dict(storage_location)) # store data self.store_message(storage_location, message)
def __init__(self, **kwargs): """ Ctypes.Structure with integrated default values. https://stackoverflow.com/questions/7946519/default-values-in-a-ctypes-structure/25892189#25892189 :param kwargs: values different to defaults :type kwargs: dict """ # sanity checks defaults = type(self)._defaults_ assert type(defaults) is types.DictionaryType # use defaults, but override with keyword arguments, if any values = defaults.copy() for (key, val) in kwargs.items(): values[key] = val # appropriately initialize ctypes.Structure #super().__init__(**values) # Python 3 syntax return Structure.__init__(self, **values) # Python 2 syntax # http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str/1827666#1827666 # https://wiki.python.org/moin/ctypes
def to_xml(self, node): if node == None or type(node) != types.DictionaryType: return None impl = xml.dom.minidom.getDOMImplementation() root_node_key = None for _node_key in node.keys(): if _node_key != '': root_node_key = _node_key break if root_node_key != None: dom = impl.createDocument(None, root_node_key, None) root = dom.documentElement self.__fetch_element(dom, root, node.get(root_node_key)) self.__indent(dom, dom.documentElement) return root.toxml() else: return None
def ExpandPathAttribute(src, attrib): """ Given a dictionary of attributes, return a list of dictionaries with all the same attributes except for the one named attrib. That one, we treat as a file path and expand into all its possible variations. """ # Do the path expansion. On any error, just return the source dictionary. path = src.get(attrib) if not path: return [src] path = encoder.MaybeNarrowPath(path); pathlist = glob.glob(path) if not pathlist: return [src] # If this isn't actually a dictionary, make it one if type(src) != types.DictionaryType: tmp = {} for key in src.keys(): tmp[key] = src[key] src = tmp # Create N new dictionaries retval = [] for path in pathlist: dst = src.copy() dst[attrib] = path retval.append(dst) return retval #end def ExpandPathAttribute
def _process_error(self, method, url, status_code, response_data): try: jsonError = json.loads(response_data) except ValueError as e: self.__logger.warning("Failed to decode result. url:%s status:%s error:%s data:%s" % (url, status_code, e, response_data)) raise TintriServerError(status_code, cause=e, message="Failed to decode result. url:%s status:%s error:%s data:%s" % (url, status_code, e, response_data)) except Exception as e: self.__logger.warning("HTTP request failed. URL:%s Status Code:%s Error:%s Text:%s" % (url, status_code, e, response_data)) raise TintriServerError(status_code, None, cause=`e`, details=response_data) if type(jsonError) == types.DictionaryType: self.__logger.info('Server error. url:%s status:%s code:%s message:%s cause:%s' % (url, status_code, jsonError['code'], jsonError['message'], jsonError['causeDetails'])) if status_code == 400: raise TintriBadRequestError(jsonError['code'], jsonError['message'], jsonError['causeDetails']) elif status_code == 401: raise TintriInvalidSessionError(jsonError['code'], jsonError['message'], jsonError['causeDetails']) elif status_code == 403: raise TintriAuthorizationError(jsonError['code'], jsonError['message'], jsonError['causeDetails']) elif status_code == 404: raise TintriAPINotFoundError(jsonError['code'], jsonError['message'], jsonError['causeDetails']) elif status_code == 500: raise TintriInternalError(jsonError['code'], jsonError['message'], jsonError['causeDetails']) else: raise TintriServerError(status_code, code=jsonError['code'], message=jsonError['message'], details=jsonError['causeDetails']) else: self.__logger.info('Server error. url:%s status:%s Unknown error:%s' % (url, status_code, response_data)) raise TintriServerError(status_code, code=None, message='Unknown error', details=response_data)
def map_to_object(m, cls): def __getobjecttype(cls, varname): from .__init__ import TintriObject if '_property_map' in dir(cls): if varname in cls._property_map.keys(): return cls._property_map[varname] return TintriObject if type(m) == types.DictionaryType: o = cls() ignoresetattr = None if hasattr(o, '_ignoresetattr'): ignoresetattr = o._ignoresetattr o._ignoresetattr = True for k in m.keys(): cls2 = __getobjecttype(cls, k) setattr(o, k, map_to_object(m[k], cls2)) if ignoresetattr: o._ignoresetattr = ignoresetattr return o elif type(m) == types.ListType: objects = [] for obj in m: objects.append(map_to_object(obj, cls)) return objects else: return m
def process_file(f, processor): try: dirpath, filename = os.path.split(f) modulename = filename[:-3] if dirpath in sys.path: sys.path.remove(dirpath) sys.path.insert(0, dirpath) module = __import__(modulename) member_names = dir(module) print('Testing file %s' % f) for name in member_names: try: attr = getattr(module, name) if isinstance(attr, Template): description = '(member name %s)' % name test_if_template(attr, description, processor) elif isinstance(attr, types.ListType): for mem in attr: description = '(element in list %s)' % name test_if_template(mem, description, processor) elif isinstance(attr, types.DictionaryType): for k in attr: description = '(%s[%s])' % (name, k) test_if_template(attr[k], description, processor) else: attr = None except Exception as e: print('Exception when testing member %s' % name) if processor.verbose: print(traceback.format_exc()) except Exception as e: print('Exception when processing file %s: %s' % (f, e)) if processor.verbose: print(traceback.format_exc())
def getAlbumJson(self, album_id, checkMasterAlbum=False): json_obj = self.fetch('album', '%s' % album_id) #if isinstance(json_obj, DictionaryType): # json_obj.update({'_cached': True, '_mqa': False if not checkMasterAlbum else self.isMasterAlbum(album_id)}) return json_obj
def dict_to_JsonObject(the_dict, name=None, ctx=None): ''' Create a JsonObject from a dictionary. The context parameter is used for recursive calls, no need to pass it from outside. :param the_dict: dictionary to base the `JsonObject` on :param ctx: context for the parser (default: None) :rtype: :class:`~katnip.legos.json.JsonObject` :return: JSON object that represents the dictionary ''' if type(the_dict) != dict: raise ValueError('expecting dictionary as first argument') if ctx is None: ctx = _JsonStringContext() members = {} for (k, v) in the_dict.items(): if v is None: val = JsonNull(name=ctx.uname(k), fuzzable=False) elif isinstance(v, types.BooleanType): val = JsonBoolean(name=ctx.uname(k), value=v, fuzzable=True) elif isinstance(v, types.StringTypes): val = JsonString(name=ctx.uname(k), value=v, fuzzable=True) elif isinstance(v, types.ListType): val = list_to_JsonArray(v, k, ctx) elif isinstance(v, types.DictionaryType): val = dict_to_JsonObject(v, k, ctx) elif isinstance(v, types.IntType): val = SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname(k)) else: raise ValueError('type not supported: %s' % type(v)) members[k] = val if name is None: name = 'obj' return JsonObject(name=ctx.uname(name, False), member_dict=members, fuzz_keys=False)
def list_to_JsonArray(the_list, name=None, ctx=None): ''' Create a JsonArray from a list. The context parameter is used for recursive calls, no need to pass it from outside. :param the_list: list to base the JsonArray on :param ctx: context for the parser (default: None) :rtype: :class:`~katnip.legos.json.JsonArray` :return: JSON object that represents the list ''' if type(the_list) != list: raise ValueError('expecting list as first argument') if ctx is None: ctx = _JsonStringContext() elements = [] for v in the_list: if v is None: elements.append(JsonNull(ctx.uname('null'), fuzzable=False)) elif isinstance(v, types.BooleanType): elements.append(JsonBoolean(ctx.uname('bool'), value=v, fuzzable=True)) elif isinstance(v, types.StringTypes): elements.append(JsonString(ctx.uname('string'), v, fuzzable=True)) elif isinstance(v, types.ListType): elements.append(list_to_JsonArray(v, None, ctx)) elif isinstance(v, types.DictionaryType): elements.append(dict_to_JsonObject(v, None, ctx)) elif isinstance(v, types.IntType): elements.append(SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname('int'))) else: raise ValueError('type not supported: %s' % type(v)) if name is None: name = 'array' return JsonArray(name=ctx.uname(name, False), values=elements)
def _required(self): return [ ("file", types.StringType), ("filetype", types.StringType), ("schema", types.DictionaryType), ("constants", types.DictionaryType) ]
def _assertDict(self, obj, sObjName=""): if type(obj) != types.DictionaryType: return self._raiseError(TypeError, "%s must be a dictionary."%sObjName)
def _get_skip_key(self, *args): key_parts = [] for arg in args: if isinstance(arg, types.StringTypes): key_parts.append(arg) elif isinstance(arg, types.DictionaryType): key_parts.append(','.join(arg.keys())) skip_key = '-'.join(key_parts) return skip_key
def flatten(l): """ Munge InfluxDB results. See also: https://stackoverflow.com/questions/21461140/flatten-an-irregular-list-of-lists-in-python-respecting-pandas-dataframes """ for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (basestring, pandas.DataFrame, types.DictionaryType)): for sub in flatten(el): yield sub else: yield el
def __fetch_element(self, dom, pelement, node): if node != None: for node_name in node.keys(): node_value = node.get(node_name) if type(node_value) == types.DictionaryType: self.__create_element(dom, pelement, node_name, node_value) elif type(node_value) == types.ListType: for node_item in node_value: self.__create_element(dom, pelement, node_name, node_item)
def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns=0, maxDepth=None): '''An insanely CPU-intensive process for finding stuff. ''' if paths is None: paths = [] if seen is None: seen = {} if eq(start, goal): paths.append(path) if seen.has_key(id(start)): if seen[id(start)] is start: return if maxDepth is not None: if maxDepth == 0: return maxDepth -= 1 seen[id(start)] = start if isinstance(start, types.DictionaryType): r = [] for k, v in start.items(): objgrep(k, goal, eq, path+'{'+repr(v)+'}', paths, seen, showUnknowns, maxDepth) objgrep(v, goal, eq, path+'['+repr(k)+']', paths, seen, showUnknowns, maxDepth) elif isinstance(start, types.ListType) or isinstance(start, types.TupleType): for idx in xrange(len(start)): objgrep(start[idx], goal, eq, path+'['+str(idx)+']', paths, seen, showUnknowns, maxDepth) elif isinstance(start, types.MethodType): objgrep(start.im_self, goal, eq, path+'.im_self', paths, seen, showUnknowns, maxDepth) objgrep(start.im_func, goal, eq, path+'.im_func', paths, seen, showUnknowns, maxDepth) objgrep(start.im_class, goal, eq, path+'.im_class', paths, seen, showUnknowns, maxDepth) elif hasattr(start, '__dict__'): for k, v in start.__dict__.items(): objgrep(v, goal, eq, path+'.'+k, paths, seen, showUnknowns, maxDepth) if isinstance(start, types.InstanceType): objgrep(start.__class__, goal, eq, path+'.__class__', paths, seen, showUnknowns, maxDepth) elif isinstance(start, weakref.ReferenceType): objgrep(start(), goal, eq, path+'()', paths, seen, showUnknowns, maxDepth) elif (isinstance(start, types.StringTypes+ (types.IntType, types.FunctionType, types.BuiltinMethodType, RegexType, types.FloatType, types.NoneType, types.FileType)) or type(start).__name__ in ('wrapper_descriptor', 'method_descriptor', 'member_descriptor', 'getset_descriptor')): pass elif showUnknowns: print 'unknown type', type(start), start return paths
def _validate(self): dict = { 'validator' : None, 'min' : None, 'max' : None, 'minstrict' : 1, 'maxstrict' : 1, } opt = self['validate'] if type(opt) is types.DictionaryType: dict.update(opt) else: dict['validator'] = opt # Look up validator maps and replace 'validator' field with # the corresponding function. validator = dict['validator'] valFunction = self._getValidatorFunc(validator, 0) self._checkValidateFunction(valFunction, 'validate', validator) dict['validator'] = valFunction # Look up validator maps and replace 'stringtovalue' field # with the corresponding function. if dict.has_key('stringtovalue'): stringtovalue = dict['stringtovalue'] strFunction = self._getValidatorFunc(stringtovalue, 1) self._checkValidateFunction( strFunction, 'stringtovalue', stringtovalue) else: strFunction = self._getValidatorFunc(validator, 1) if strFunction == validator: strFunction = len dict['stringtovalue'] = strFunction self._validationInfo = dict args = dict.copy() del args['validator'] del args['min'] del args['max'] del args['minstrict'] del args['maxstrict'] del args['stringtovalue'] self._validationArgs = args self._previousText = None if type(dict['min']) == types.StringType and strFunction is not None: dict['min'] = apply(strFunction, (dict['min'],), args) if type(dict['max']) == types.StringType and strFunction is not None: dict['max'] = apply(strFunction, (dict['max'],), args) self._checkValidity()
def __parse(self, node): if node == None: return None node_data = {} children = node.childNodes if len(children) > 0: for child in children: child_name = child.nodeName if child_name != None and child_name.strip() != '': if child.nodeType == child.ELEMENT_NODE: child_value = self.__parse(child) elif child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NODE: child_value = child.data.strip() if child.data != None else child.data temp_node = node_data.get(child_name) if temp_node == None and child_value != None and child_value != '': temp_node = child_value else: if type(temp_node) == types.DictionaryType or type(temp_node) == types.UnicodeType: temp_node = [temp_node, child_value] elif type(temp_node) == types.ListType: temp_node.append(child_value) if temp_node != None: if child.nodeType == child.TEXT_NODE: child_name = '_node_' elif child.nodeType == child.CDATA_SECTION_NODE: child_name = '_cdata_' node_data[child_name] = temp_node if node.attributes != None: for attr_key in node.attributes.keys(): attribute = node.attributes[attr_key] attr_name = attribute.name if attr_name != None and attr_name != '': attr_value = {'_attr_' : attribute.value} temp_node = node_data.get(attr_name) if temp_node == None: temp_node = attr_value else: if type(temp_node) == types.DictionaryType: temp_node = [temp_node, attr_value] elif type(temp_node) == types.ListType: temp_node.append(attr_value) if temp_node != None: node_data[attr_name] = temp_node return node_data