2

I have pythonnet v 2.3.0 installed. I have a C# class library which I use in Python. I have a Point class (a code snippet):

public Point(double x, double y)
{
    this.x = x;
    this.y = y;
}

public override string ToString()
{
    return $"Point({x}, {y})";
}

When I work with this class library in Python (in Python shell):

>>> p1 = Point(10,15)
>>> p1
<Geometry.Point object at 0x000000000558F828>
>>> str(p1)
'Point(10, 15)'

Because I override the ToString(), when I run str(p1) I see my custom view of the object. However, when I just access a variable p1, then it goes to the __repr__() method under the hood which gives me ugly <Geometry.Point object at 0x000000000558F828>.

Is there a method in C# class that is possible to override so that pythonnet would use that method when getting the __repr__?

https://github.com/pythonnet/pythonnet/issues/680

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Alex Tereshenkov
  • 3,340
  • 8
  • 36
  • 61
  • Check out their repository. A search for "repr" shows that you **may** (I'm guessing) be able to define a static method in your type with the following signature: `pulic static IntPtr tp_repr(IntPtr ob)`. Some of their implementations had to specify the `new` modifier as well. https://github.com/pythonnet/pythonnet/search?utf8=✓&q=Repr&type= – pinkfloydx33 Jun 03 '18 at 12:38
  • My guess would be: `public static IntPtr tp_repr(IntPtr ob)  { var self = (Point)GetManagedObject(ob);  return Runtime.PyString_FromString($"Point({self.x}, {self.y})"); }` Please understand this is entirely a guess. I've never used this Library before and only spent a few minutes reviewing the source after not finding anything in their docs – pinkfloydx33 Jun 03 '18 at 12:47
  • Ugh... Looking further it looks like some of those methods are internal to the library. Though I think it might be a fair starting point for you to look through their code base and see if you can find something that *can* be used. I'm still fairly confident you need to include that static method – pinkfloydx33 Jun 03 '18 at 12:56
  • @pinkfloydx33, thanks will dig deeper. I think `IntPtr` is used only for representation of integers, are you sure this can be used for custom classes? https://msdn.microsoft.com/en-us/library/system.intptr%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 – Alex Tereshenkov Jun 03 '18 at 13:35
  • IntPtr has nothing to do with integers necessarily. It can represent just about anything. It's used for interop between managed and unmanaged code – pinkfloydx33 Jun 03 '18 at 14:26

0 Answers0