From 42e36100a85e010f83b0d1ecf069a99ee18ea918 Mon Sep 17 00:00:00 2001 From: Joakim Hove Date: Wed, 23 Feb 2022 11:01:00 +0100 Subject: [PATCH] Export RawString as std::string to Python --- opm/input/eclipse/Deck/DeckItem.hpp | 1 + python/cxx/deck_keyword.cpp | 15 ++++++++++++++- python/tests/test_parse.py | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/opm/input/eclipse/Deck/DeckItem.hpp b/opm/input/eclipse/Deck/DeckItem.hpp index 15af0d8a3..fb78e4ecf 100644 --- a/opm/input/eclipse/Deck/DeckItem.hpp +++ b/opm/input/eclipse/Deck/DeckItem.hpp @@ -130,6 +130,7 @@ namespace Opm { bool is_double() { return type == get_type< double >(); }; bool is_int() { return type == get_type< int >() ; }; bool is_string() { return type == get_type< std::string >(); }; + bool is_raw_string() { return type == get_type< RawString >(); }; UDAValue& get_uda() { return uval[0]; }; diff --git a/python/cxx/deck_keyword.cpp b/python/cxx/deck_keyword.cpp index 6f9481f85..f85e3abfc 100644 --- a/python/cxx/deck_keyword.cpp +++ b/python/cxx/deck_keyword.cpp @@ -148,6 +148,19 @@ std::string get_uda_str(DeckItem * item) return uda.get(); } +/* + When exporting values to Python RawString and std::string are treated + identically. +*/ +std::string get_string(DeckItem * item, std::size_t index) { + if (item->is_string()) + return item->get(index); + else if (item->is_raw_string()) + return item->get(index); + else + throw std::logic_error("Tried to get string from item which is not string"); +} + } void python::common::export_DeckKeyword(py::module& module) { @@ -242,7 +255,7 @@ void python::common::export_DeckKeyword(py::module& module) { .def("is_double", &DeckItem::is_double) .def("is_int", &DeckItem::is_int) .def("is_string", &DeckItem::is_string) - .def("get_str", &DeckItem::get) + .def("get_str", &get_string) .def("get_int", &DeckItem::get) .def("get_raw", &DeckItem::get) .def("get_uda", &DeckItem::get) diff --git a/python/tests/test_parse.py b/python/tests/test_parse.py index 383af5de8..f116c2790 100644 --- a/python/tests/test_parse.py +++ b/python/tests/test_parse.py @@ -100,6 +100,24 @@ KEYWORD self.assertEqual(len(deck), 1) + def test_raw_string_output(self): + deck_string = """ +UDQ + DEFINE WUOPR2 WOPR '*' * WOPR '*' / + DEFINE WUGASRA 3 - WGLIR '*' / +/ + """ + + parse_context = ParseContext( ) + parser = Parser() + parse_context.ignore_keyword("KEYWORD") + deck = parser.parse_string( deck_string ) + udq = deck[0] + s = "" + for rec in udq: + for item in rec: + s += item.get_str(0) + if __name__ == "__main__": unittest.main()