tags:

views:

201

answers:

4

Is there possibility to add method to object class, to use method on all objects?

A: 
>>> object.test = "Test"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can't set attributes of built-in/extension type 'object'

Doesn't look like it. (Python 2.5.1)

Georg
so the answer is NO? ))
dynback.com
I think so, but I'm not 100% sure.
Georg
+7  A: 

In Python attributes are implemented using a dictionary :

>>> t = test()
>>> t.__dict__["foo"] = "bla"
>>> t.foo
'bla'

But for "object", it uses a 'dictproxy' as an interface to prevent such assignement :

>>> object.__dict__["test"] = "test"
TypeError: 'dictproxy' object does not support item assignment

So no, you can't.

NB : you can't modify the metaclass Type directly neither. But as Python is very flexible, I am sure a Guru could find a way to achieve what you want. Any black wizard around here :-) ?

e-satis
Maybe trough metaclasses?
Georg
No, metaclasses will only affect classes and objects that use them, not existing built-in types such as object, int, str, float, and so on. So, "all objects" is just not going to happen. (You can stick new functions into __builtin__ of course, which will make them just as widely available, but they're not going to be METHODS of the object built-in type).
Alex Martelli
A: 

It's called monkeypatching. Please don't do it.

S.Lott
There can be good reason to monkey patch. That's how 37signals spread the security patches for ROR. I don't think we can call them noobs...
e-satis
Generally, in Python, you can easily subclass things and don't need to mess with monkeypatching. This isn't Ruby, this is Python.
S.Lott
Python and ruby have the same flexibility when it comes to subclassing. If the pratice remains, there must be a reason. In programming, saying "don't do" something without a good pro and con speech is almost rude, IMHO, espacially with advanced pratices.
e-satis
Many practices remain which are really abysmally bad. The reasons include obstinacy, misinformation, ignorance of better techniques. Sorry, but, "don't do it" is essential advice. There's no pro -- the con is that your code is now unmaintainable since a change to the base class mysteriously invalidates the monkeypatch.
S.Lott
+2  A: 

No, Python's internals take great care to make built-in types NOT mutable -- very different design choices from Ruby's. It's not possible to make object "monkeypatchable" without deeply messing with the C-coded internals and recompiling the Python runtime to make a very different version (this is for the classic CPython, but I believe exactly the same principle holds for other good implementations such as Jython and IronPython, just s/C/Java/ and S/C/C#/ respectively;-).

Alex Martelli