On Tue, Feb 9, 2021 at 4:53 AM Kazantcev Andrey <hec...@yandex.ru> wrote: > I decided to figure out why it is impossible to change methods of built-in > types and found > ``` > if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { > PyErr_Format( > PyExc_TypeError, > "can't set attributes of built-in/extension type '%s'", > type->tp_name); > return -1; > } > ``` > in function type_setattro. > If comment this line and try to patch method __eq__ on the list for example > the code will work as expected
I removed this "if" and tested: $ ./python Python 3.10.0a5+ (heads/master-dirty:ab2d481639, Feb 16 2021, 00:55:58) >>> "a" == "b" False >>> str.__eq__=lambda x,y: True >>> "a" == "b" True It seems technically possible to override attributes/methods of built-in types, but the question is more if it's desirable? IMO it goes against the specification of the Python language itself. For example, in Python, it's not allowed to add methods to built-in types. Example (with the removed "if") >>> str.strip_spaces=lambda s: s.strip(" \t") >>> " a ".strip_spaces() 'a' The problem is that built-in types are shared by everything, and adding non-standard methods means that code using it becomes non-standard (cannot be used on an "unmodified" Python). Do you want to see projects popping up on PyPI which rely on a special (non-standard) str methods like strip_spaces()? I didn't use Ruby on Rails, but the feedback that I heard is that the ability to extend built-in types is appealing, but it is problematic in practice. Victor -- Night gathers, and now my watch begins. It shall not end until my death. _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-le...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/WOEGG2G5PKIXFVB5YOF7MI6OPNTCYQCZ/ Code of Conduct: http://python.org/psf/codeofconduct/