Skip to content
Advertisement

unexpected behavior with EnumMeta class

I defined an IntEnum for some weather codes and provided a metaclass.

JavaScript

as show above it functions as expected when passed into a dict.

JavaScript

but if I change the method name of names to keys like …

JavaScript

I get an unexpected result

JavaScript

It was my understanding that dict calls the __iter__ method under the hood to create a __new__ dict. Why does the keys method name change the behavior?

Advertisement

Answer

When using dict to construct dictionary objects, it will create an empty dictionary first. If there are arguments, the arguments will be passed to its update method. It’s not convenient to directly show the C code of dict.update, so the MutableMapping.update method in _collections_abc.py is provided here, from which we can see the update idea of dict.update:

JavaScript

When the other passed in is not a mapping, MutableMapping will first check whether the other has keys method. If so, it will try to iterate and get the corresponding value to update, rather than directly iterate over the other object. It happens that EnumMeta.__getitem__ method gets the enumeration object itself according to its name, so you get a dictionary with name as the key and enumeration object as the value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement