Create str representations in Python modules

Description

This MR adds auto-writing of string methods to our generated classes. As I understand it, repr should produce a representation of the class which can be copy-pasted into a Python interpreter. Given this, and that attrs generates this for us, I don't touch __repr__. Instead, I write a __str__ method which does provide helpful information. As a model developer, this would be super handy to have I think because you can instantly see model parameters etc. Some example output below

# tests/test-data/arrays/scratch.py
import pint

from generated.arrays import ArrayHandling


Quantity = pint.get_application_registry().Quantity


fs = Quantity([1, 2, 3, 4, 5, 6, 7], "1 / month")
ds = Quantity([[1, 2], [1, 2, ]], "1 / month")

inst = ArrayHandling()
print(repr(inst))
print(str(inst))

inst = ArrayHandling.from_new_connection()
print(repr(inst))
print(inst)

inst = ArrayHandling.from_build_args(fixed_shape=fs, deferred_shape=ds)
print(repr(inst))
print(inst)

# Gives
ArrayHandling(model_index=-1)
Uninitialised ArrayHandling(model_index=-1)
ArrayHandling(model_index=1)
ArrayHandling(model_index=1, fixed_shape=[0.0 0.0 0.0 0.0 0.0 0.0 0.0] / month, deferred_shape could not be retrieved)
ArrayHandling(model_index=2)
ArrayHandling(model_index=2, fixed_shape=[1.0 2.0 3.0 4.0 5.0 6.0 7.0] / month, deferred_shape=[[1.0 2.0] [1.0 2.0]] / month)
# tests/test-data/derived_type/scratch.py
import pint

from generated.derived_type_parent import DerivedTypeParent, DerivedType


Quantity = pint.get_application_registry().Quantity


k = Quantity(3.2, "1 / month")

inst = DerivedTypeParent()
print(repr(inst))
print(str(inst))

inst = DerivedTypeParent.from_new_connection()
print(repr(inst))
# This seg faults, bit hard to wrap that error...
# print(inst)

inst = DerivedTypeParent.from_build_args(child=DerivedType.from_build_args(k=k))
print(repr(inst))
print(inst)

# Gives
DerivedTypeParent(model_index=-1)
Uninitialised DerivedTypeParent(model_index=-1)
DerivedTypeParent(model_index=1)
DerivedTypeParent(model_index=2)
DerivedTypeParent(model_index=2, child=DerivedType(model_index=1, k=3.2 / month))

Merge Request Steps

Please confirm that this pull request has done the following:

  • Tests added
  • Documentation added (where applicable)
  • Changelog item added to changelog/.
Edited by Zebedee Nicholls

Merge request reports

Loading