[IronPython] Trying to set methods on "built-in" classes fails silently

Giles Thomas giles.thomas at resolversystems.com
Thu Jan 12 22:35:35 CET 2006


Hi,

I suspect it's not something anyone's likely to come across often, but 
if you try to rebind a method on a built-in class,  no exception will be 
thrown but it will not be changed.  An example:

You can rebind methods on regular classes easily:

---
 >>> class C:
...   def m(self):
...     return 2
...
 >>> c = C()
 >>> c.m()
2
 >>> def n():
...   return 3
...
 >>> c.m = n
 >>> c.m()
3
---

However, when you try to do this with a CLR class there's no warning, 
but it doesn't work:

---
 >>> f = Form()
 >>> f.ToString()
'System.Windows.Forms.Form, Text: '
 >>> def newToString():
...   return "Hello, world!"
...
 >>> f.ToString = newToString
 >>> f.ToString()
'System.Windows.Forms.Form, Text: '
 >>> f.ToString == newToString
False
---

The behaviour when you try to set arbitrary attributes on the built-in 
classes is nicer, I think:

---
 >>> f.foobar = 23
Traceback (most recent call last):
    at <shell>
TypeError: can't set arbitrary attributes on built-in type 
System.Windows.Forms.Form
---

I've confirmed this in the beta and in 0.9.5

(I hasten to add that I'm not recommending rebinding methods as standard 
practive...)


Cheers,

Giles
-- 
Giles Thomas
Resolver Systems
giles.thomas at resolversystems.com
We're hiring! http://www.resolversystems.com/jobs/



More information about the Ironpython-users mailing list