On 31 July 2018 at 01:35, Jonathan Fine
Hi Jamesie
Thank you for your question. You asked why not
c = MyClass o = c()
def c.foo(cls): ... def o.bar(self): ...
I've the same same query, but never had the courage to ask. So that you for asking. And also giving me a chance to share my thoughts.
It's essentially due to the fact that while we deliberately allow runtime monkeypatching (as it's sometimes the best available answer), we also strongly encourage the idea of treating it as a last resort option (outside specific use cases like testing). So if you want to define methods on a class, the strongly preferred place to define them is inside the class definition, where they're easy for future maintainers of that class to find. If you need to replace them for some reason, it will preferably be within a temporary bounded scope, using a tool like unittest.mock.patch, rather than as a permanent change that affects every other use of the class within the process. Cheers, Nick. P.S. While it's *not* explicitly part of Python's design rationale, http://connascence.io/locality.html and the rest of that site provide some good info on the kinds of problems that "action at a distance" effects, like monkeypatching class definitions, can cause in a code base. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia