解析XSD文件遇unhashable type: 'set'错误,求Python解决方案
解决XBRL解析XSD时的
unhashable type: 'set'及可变类型错误 问题场景
解析XSD文件时触发unhashable type: 'set'错误,尝试将imported_schema_uris改为{}(字典)后,又出现可变类型相关错误。原始代码如下:
from xbrl.taxonomy import parse_taxonomy_url from xbrl.cache import HttpCache import os def parse_taxonomy_from_url(schema_url): cache_path = './cache' if not os.path.exists(cache_path): os.makedirs(cache_path) # Ensure the cache directory exists cache = HttpCache(cache_path) # Create an instance of HttpCache imported_schema_uris = set() # Initialize an empty set for imported schema URIs # Debugging information print(f"Cache directory: {cache_path}") print(f"Schema URL: {schema_url}") print(f"Imported Schema URIs: {imported_schema_uris}") # Parse the taxonomy schema from the given URL try: taxonomy_schema = parse_taxonomy_url(schema_url=schema_url, cache=cache, imported_schema_uris=imported_schema_uris) return taxonomy_schema except Exception as e: print(f"An error occurred: {e}") return None # Example usage schema_url = 'http://test.xsd' # Replace with a valid URL parsed_schema = parse_taxonomy_from_url(schema_url) if parsed_schema: print("Taxonomy schema parsed successfully!") else: print("Failed to parse taxonomy schema.")
问题原因
parse_taxonomy_url函数的imported_schema_uris参数要求传入可哈希的不可变类型(用于内部缓存、去重或作为字典键)。而set(集合)和dict(字典)都是可变类型,不可哈希,因此触发错误。
解决方案
将imported_schema_uris初始化为空元组(tuple)——元组是不可变且可哈希的类型,符合函数参数要求。
修改后的代码
from xbrl.taxonomy import parse_taxonomy_url from xbrl.cache import HttpCache import os def parse_taxonomy_from_url(schema_url): cache_path = './cache' if not os.path.exists(cache_path): os.makedirs(cache_path) # 确保缓存目录存在 cache = HttpCache(cache_path) # 创建HttpCache实例 # 改用空元组作为初始值,满足可哈希要求 imported_schema_uris = () # 调试信息 print(f"缓存目录: {cache_path}") print(f"Schema URL: {schema_url}") print(f"已导入Schema URIs: {imported_schema_uris}") # 解析给定URL的分类法Schema try: taxonomy_schema = parse_taxonomy_url(schema_url=schema_url, cache=cache, imported_schema_uris=imported_schema_uris) return taxonomy_schema except Exception as e: print(f"发生错误: {e}") return None # 示例使用 schema_url = 'http://test.xsd' # 替换为有效的URL parsed_schema = parse_taxonomy_from_url(schema_url) if parsed_schema: print("分类法Schema解析成功!") else: print("分类法Schema解析失败。")
进阶处理(如需累积导入URI)
如果需要提前收集已导入的URI,可先用集合记录,传入函数时转成元组:
# 用集合临时存储已导入URI imported_uris_set = set() # 传入前转换为元组 taxonomy_schema = parse_taxonomy_url( schema_url=schema_url, cache=cache, imported_schema_uris=tuple(imported_uris_set) )
新手提示
- Python中,可变类型(list、set、dict)不可哈希,不能作为字典的键或放入集合;不可变类型(tuple、str、int、float)可哈希,适合这类场景。
- 调用第三方库函数时,若遇到类型错误,优先查看函数参数的官方文档,确认预期类型。
内容的提问来源于stack exchange,提问作者Arne Banck
相关产品推荐
相关产品推荐

