python - Is it reasonable to use type(a) as a dictionary key? -


i trying store files in dictionary depending on type. this, using pygments api follow:

# initialization of self.files dictionary self.files = dict() # scanning , categorizing files 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] 

but, now, when passing code through pylint3, warning telling me should use isinstance() in place of type() (unidiomatic-typecheck).

the best way workaround warning found far follow:

self.files = dict() 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] 

but, solve problem ? and, moreover, started doubt using type key in dictionary robust enough.

so, there more suitable , robust ways do? solution arguments welcome.

using type() output, object, key fine. ignore warning in case.

i'd use dict.setdefault() or collections.defaultdict() extend list value:

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

or

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

however, on python 3, investigate if functools.singledispatch() used handle use-case instead. calls registered function given object type, taken first argument, , supports subclasses.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -