【问题标题】:Is it reasonable to use type(a) as a dictionary key?使用 type(a) 作为字典键是否合理?
【发布时间】:2016-05-04 16:32:47
【问题描述】:

我正在尝试根据文件类型将文件存储在字典中。为此,我使用pygments API 如下:

# Initialization of the self.files dictionary
self.files = dict()
# Scanning and categorizing the files
for file in files:
    lexer = guess_lexer__for_filename(file, None)
    if type(lexer) in self.files:
        self.files[type(lexer)].append(file)
    else:
        self.files[type(lexer)] = [file]

但是,现在,当通过pylint3 传递此代码时,我收到一条警告,告诉我应该使用isinstance() 代替type()(unidiomatic-typecheck)。

到目前为止,我发现解决此警告的最佳方法如下:

self.files = dict()
for file in files:
    lexer = guess_lexer__for_filename(file, None)
    if lexer.__class__ in self.files:
        self.files[lexer.__class__].append(file)
    else:
        self.files[lexer.__class__] = [file]

但是,它真的能解决问题吗?而且,我开始怀疑在字典中使用类型作为键是否足够健壮。

那么,有没有更合适、更稳健的方法呢?欢迎任何具有良好论据的解决方案。

【问题讨论】:

    标签: python dictionary pygments


    【解决方案1】:

    使用type() 输出,一个对象,作为一个键就好了。 Ignore that warning 在这种情况下。

    我会使用dict.setdefault()collections.defaultdict() 来扩展列表值:

    self.files = {}
    
    for file in files:
        lexer = guess_lexer__for_filename(file, None)
        self.files.setdefault(type(lexer), []).append(file)
    

    from collections import defaultdict
    
    self.files = defaultdict(list)
    
    for file in files:
        lexer = guess_lexer__for_filename(file, None)
        self.files[type(lexer)].append(file)
    

    但是,在 Python 3 上,您可以调查是否可以使用 functools.singledispatch() 来处理您的用例。它为给定的对象类型调用一个注册函数,取自第一个参数,并支持子类。

    【讨论】:

    • singledispatch() 不错,但不符合我的预期用途。而且,我不知道setdefault/defaultdict 技巧,我一定会使用它。非常感谢!
    猜你喜欢
    • 2011-10-25
    • 2011-10-25
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 2013-10-14
    相关资源
    最近更新 更多