4 ms·
> instance checking and class-hook hacks These are not remotely "hacks" in Python. They are up-front, first class patterns for Python metaclasses. I do agree t
by p4wnc6 10y ago
> instance checking and class-hook hacks
These are not remotely "hacks" in Python. They are up-front, first class patterns for Python metaclasses. I do agree that monkeypatching is a hack, and is unfortunately relied upon too often in Python.
- Chris2048 10y agoDepends which Python - Py3 is a bit more robust wrt metaclasses. instance checking on a overridden magic method certainly is a hack, I don't know what youy mean by "first class pattern" - Why add the possibility that the instanceof mechanism has been messed with, thereby throwing off alot of reasonable assumptions about the check?
- p4wnc6 10y agoI 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.