Skip to content

Commit ddd806b

Browse files
authored
Merge pull request #1047 from compas-dev/net-tostring
Add ToString to data class
2 parents da6f0e6 + 2cc0b2d commit ddd806b

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2020
* Added `Data.guid` to pickle state.
2121
* Added `Assembly.find_by_key` to locate parts by key.
2222
* Added `clear_edges` and `clear_nodes` to `NetworkArtist` for ghpython.
23+
* Added `ToString` method to `Data` to ensure that Rhino/Grasshopper correctly casts objects to string.
2324

2425
### Changed
2526

src/compas/data/data.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,18 @@ def data(self):
185185
def data(self, data):
186186
raise NotImplementedError
187187

188+
def ToString(self):
189+
"""Converts the instance to a string.
190+
191+
This method exists for .NET compatibility. When using IronPython,
192+
the implicit string conversion that usually takes place in CPython
193+
will not kick-in, and in its place, IronPython will default to
194+
printing self.GetType().FullName or similar. Overriding the `ToString`
195+
method of .NET object class fixes that and makes Rhino/Grasshopper
196+
display proper string representations when the objects are printed or
197+
connected to a panel or other type of string output."""
198+
return str(self)
199+
188200
@property
189201
def jsonstring(self):
190202
return compas.json_dumps(self.data)

tests/compas/data/test_data.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from compas.data import Data
2+
3+
def test_string_casting():
4+
class TestClass(Data):
5+
def __init__(self, i):
6+
self.i = i
7+
8+
def __str__(self):
9+
return "TestClass {}".format(self.i)
10+
11+
test = TestClass(42)
12+
assert str(test) == "TestClass 42"

0 commit comments

Comments
 (0)