PyObject.FromManagedObject(value); does not convert C# bool to Python bool #2417
Answered
by
lostmsu
Veselin-Stoilov
asked this question in
Q&A
Environment
Details
public static string PythonTestRunner(string pyDirPath, string pyModule, string pyMethod, Dictionary<string, object> argsDict)
{
try
{
using (Py.GIL())
{
dynamic os = Py.Import("os");
dynamic sys = Py.Import("sys");
string currentPath = os.getcwd().ToString();
string fullDirPath = os.path.join(currentPath, pyDirPath).ToString();
sys.path.append(fullDirPath);
dynamic module = Py.Import(pyModule);
dynamic method = module.GetAttr(pyMethod);
PyDict kwargs = new PyDict();
foreach (var kvp in argsDict)
{
PyObject pyKey = new PyString(kvp.Key);
PyObject pyValue = ConvertToPyObject(kvp.Value);
kwargs[pyKey] = pyValue;
}
dynamic resultMessage = method.Invoke(new PyTuple(), kwargs);
return (string)resultMessage;
}
}
catch (Exception ex)
{
// Log the error and rethrow it
throw;
}
}public static PyObject ConvertToPyObject(dynamic value)
{
if (value == null)
return PyObject.None;
else if (value is string)
return new PyString(value);
else if (value is int)
return new PyInt(value);
else if (value is bool)
return PyObject.FromManagedObject(value);
else
return PyObject.FromManagedObject(value);
}# test_module.py
def test_method(param1: bool):
error_messages = []
if not isinstance(param1, bool):
error_messages.append(f"testBoolTrue is not a boolean, but {type(param1).__name__}")
# Determine message
result_message = "Invalid data types: " + ", ".join(error_messages)
return result_message
|
Answered by
lostmsu
Jul 15, 2024
Replies: 2 comments
|
It's not supposed to.
|
0 replies
Answer selected by
Veselin-Stoilov
|
@lostmsu Thanks for your input. What should I then use to convert C# bool to Python bool? Is there a specific method or class in Pythonnet to achieve this since PyBool object is not available? |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's not supposed to.
Reference