tags:

views:

129

answers:

1

I'm trying to implement a class in C# with a method that intercepts the Python __setattr__ and __getattr__ magic methods. I found this bug report:

http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=8143

But that is from 2008, and nowhere can I find ICustomAttributes or PythonNameAttribute. I don't see anything useful in Interfaces.cs either. Can someone point me in the right direction?

+4  A: 

I don't use IronPython, so I may be completely wrong, but here is what I would suppose.

Given that Dynamic Language Runtime is now fully integrated in .NET 4.0 and IronPython is based on DLR, you should be able to use the standard .NET way of creating objects that handle setting/getting of non-existing members/attributes/properties. This can be done by implementing the IDynamicMetaObjectProvider interface. A simpler way is to inherit from DynamicObject, which provides default implementation for most of the methods and add only the method you need (see members of DynamicObject):

class MyObject : DynamicObject {
  public override bool TryGetMember
      (GetMemberBinder binder, out object result) {
    string name = binder.Name;
    // set the 'result' parameter to the result of the call
    return // true to pretend that attribute called 'name' exists
  }

  public override bool TrySetMember
      (SetMemberBinder binder, object value) {
    // similar to 'TryGetMember'
  }  
}

In C# you can use this object thanks to dynamic. IronPython should treat it in the same way!

Tomas Petricek
At first, when I read your answer, I was like, "eh". I tried it. Played around with it. And it is cool. Have an upvote!
yodaj007
@yodaj007: glad it worked (it also shows that DLR works as expected, which is good to know)!
Tomas Petricek