polish support for python3

This commit is contained in:
Laurent Perron
2016-03-16 13:34:47 +01:00
parent 03c648bc2c
commit 937d021dfd
3 changed files with 37 additions and 5 deletions

View File

@@ -2,9 +2,21 @@
# Detect python3
ifeq ("$(PYTHON_VERSION)","3.2")
PYTHON3 = true
SWIG_PYTHON3_FLAG=-py3 -DPY3
endif
ifeq ("$(PYTHON_VERSION)","3.3")
PYTHON3 = true
SWIG_PYTHON3_FLAG=-py3
SWIG_PYTHON3_FLAG=-py3 -DPY3
endif
ifeq ("$(PYTHON_VERSION)","3.4")
PYTHON3 = true
SWIG_PYTHON3_FLAG=-py3 -DPY3
endif
ifeq ("$(PYTHON_VERSION)","3.5")
PYTHON3 = true
SWIG_PYTHON3_FLAG=-py3 -DPY3
endif
# Main target

View File

@@ -47,6 +47,7 @@ namespace operations_research {
%pythoncode {
import numbers
import sys
from ortools.linear_solver.linear_solver_natural_api import OFFSET_KEY
from ortools.linear_solver.linear_solver_natural_api import inf
from ortools.linear_solver.linear_solver_natural_api import LinearExpr
@@ -121,8 +122,12 @@ from ortools.linear_solver.linear_solver_natural_api import VariableExpr
else:
coeffs = expr.GetCoeffs()
objective.AddOffset(coeffs.pop(OFFSET_KEY, 0.0))
for v, c, in coeffs.iteritems():
objective.SetCoefficient(v, float(c))
if sys.version_info >= (3, 0):
for v, c, in list(coeffs.items()):
objective.SetCoefficient(v, float(c))
else:
for v, c, in coeffs.iteritems():
objective.SetCoefficient(v, float(c))
def Maximize(self, expr):
objective = self.Objective()
@@ -133,8 +138,12 @@ from ortools.linear_solver.linear_solver_natural_api import VariableExpr
else:
coeffs = expr.GetCoeffs()
objective.AddOffset(coeffs.pop(OFFSET_KEY, 0.0))
for v, c, in coeffs.iteritems():
objective.SetCoefficient(v, float(c))
if sys.version_info >= (3, 0):
for v, c, in list(coeffs.items()):
objective.SetCoefficient(v, float(c))
else:
for v, c, in coeffs.iteritems():
objective.SetCoefficient(v, float(c))
} // %pythoncode
}

View File

@@ -58,9 +58,15 @@ namespace operations_research {
%typemap(argout) CppType* const, CppType* {
std::string encoded_protobuf;
$1->SerializeToString(&encoded_protobuf);
#if defined(PY3)
PyObject* const python_encoded_protobuf =
PyBytes_FromStringAndSize(encoded_protobuf.c_str(),
encoded_protobuf.size());
#else // PY3
PyObject* const python_encoded_protobuf =
PyString_FromStringAndSize(encoded_protobuf.c_str(),
encoded_protobuf.size());
#endif // PY3
if (python_encoded_protobuf != nullptr) {
PyObject* const result = PyObject_CallMethod(
$input, const_cast<char*>("ParseFromString"),
@@ -79,8 +85,13 @@ namespace operations_research {
if (clss != nullptr) {
std::string encoded_protobuf;
$1.SerializeToString(&encoded_protobuf);
#if defined(PY3)
PyObject* const python_encoded_protobuf = PyBytes_FromStringAndSize(
encoded_protobuf.c_str(), encoded_protobuf.size());
#else // PY3
PyObject* const python_encoded_protobuf = PyString_FromStringAndSize(
encoded_protobuf.c_str(), encoded_protobuf.size());
#endif // PY3
PyObject* const result = PyObject_CallMethod(
clss, const_cast<char*>("FromString"),
const_cast<char*>("(O)"),