[IronPython] Using Python special methods in C#

Dino Viehland dinov at exchange.microsoft.com
Sun Jul 13 20:04:19 CEST 2008

Srivatsn's blog is an important piece of the puzzle, but the more general answer is implementing the __*__ method directly should always work.  If it doesn't then it's a bug - like where __repr__ wasn't working w/o implementing the interface until recently.

But there is a good reason to not implement the __*__ method - and that's ensuring that your objects will work good in a multi-language environment.  What IronPython does to expose .NET objects into Python is it maps a large number of .NET interfaces and methods into Python methods.  If you'd like to see the all of the mappings they're contained entirely in TypeInfo.cs.  So instead of implementing __getitem__ you can implement a C# indexer,  instead of __enter__/__exit__ you can implement IDisposable - assuming you're not doing more interesting things w/ __enter__/__exit__, etc...  If there's some mapping that you think should exist but we don't have let us know - for example until recently we had overlooked mapping IDisposable.

To get the best interop if there's a .NET interface or operator method that maps onto the Python methods you should use that.  That includes the extended operators that we've defined for the DLR default binder like GetCustomMember as Srivatsn's blog demonstrates.  Otherwise fallback to the __*_- method.

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Michael Foord
Sent: Sunday, July 13, 2008 10:21 AM
To: Discussion of IronPython
Subject: Re: [IronPython] Using Python special methods in C#

Dan Eloff wrote:
> Something I've found a little difficult in C# is python special
> methods. It seems sometimes you can just declare them on the C# class,
> (__repr__?) and they will work, other times you need to implement an
> interface (__call__?) is there any place this is documented?
> I'm a little confused about how to add special methods on C# classes.
> I want to add __getattr__ to a C# class (actually a subclass of
> PythonDictionary), and I have no idea how.

This example from Srivatsn shows you how:


> Thanks,
> -Dan
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com


Users mailing list
Users at lists.ironpython.com

More information about the Ironpython-users mailing list