If the answer to these questions is yes, it's probably a good idea to not stop here, and consider the next option instead. Does it actually make sense for your object to be passed around as a set of key-value pairs, or as keyword arguments and values? Does accessing it by key- just like a dictionary- really make sense? Would you also expect your object to have other standard mapping methods such as items, values, get? Do you want to support the in keyword and equality checks ( =)? If you implement another nonstandard behavior for _iter_ (returning values instead of keys), it could be surprising for other people using your code unless it is very obvious why this would happen.ĮMPHASIZED: Just because you CAN use the mapping protocol, does NOT mean that you SHOULD do so. when cast to a dict ( dict(m)).īut note also that with regular dictionaries, if you cast to a list, it will give the KEYS back, and not the VALUES as you require. So it is possible- and might be sometimes convenient- to cause the object to have different behavior when used as an iterable (e.g., list(m)) vs. Note that the mapping protocol takes precedence over the _iter_ method when casting an object to a dict directly (without using kwarg unpacking, i.e. Let's say I've got a simple class in python class Wharrgarbl(object):ĭef _init_(self, a, b, c, sum, version='old'):
0 Comments
Leave a Reply. |