5 ms·
I mean it is supported directly with __instancecheck__ or __subclasshook__ .. explicitly to allow you to create metaclasses with custom implementations of insta
by p4wnc6 10y ago
I mean it is supported directly with __instancecheck__ or __subclasshook__ .. explicitly to allow you to create metaclasses with custom implementations of instance checking or subclassing. To call use of this a hack is similar to saying that overriding __getitem__ is a hack. In Python, it's not a hack, it's a normal, common way of doing many things.
You'd mess with the isinstance mechanism exactly when doing so made engineering sense. In Python, making assumptions about what isinstance is doing is a very bad idea, would indicate novice Python understanding -- just like picking up some other class (like say, pandas DataFrame) and assuming something "reasonable" about what __getitem__ does would be a bad idea -- __getitem__ is heavily overloaded for various design and performance reasons in Pandas (and in many, many libraries).
You can't (and shouldn't want to) pick up any old class in Python and assume things like operator overloads, hashing, instance checking, item getting, serialization, iteration, etc. etc., work under "reasonable assumptions." Either the class authors implemented the trickery in some way that virtually never impacts anyone, or else you need to know the gory implementation details to effectively reason about it. My experience has been that you should always assume the latter until you have strong evidence of the former.