from pydrake.common.value import Value
from pydrake.math import RigidTransform
from pydrake.systems.primitives import ConstantValueSource

def _create_context_value_reference():
    """Returns a reference to a C++ object whose storage comes from inside a Context.
    The return value should keep the entire (otherwise-unused) context alive.
    """
    system = ConstantValueSource(Value(RigidTransform()))
    context = system.CreateDefaultContext()
    return system.get_output_port().Eval(context)

# Check that the object still retains its correct value.
X = _create_context_value_reference()
print(X)
assert X.IsExactlyIdentity()# Re-check that the object still retains its correct value.
print(X)
assert X.IsExactlyIdentity()