fix: convert arguments names that are keywords reserved by Python

pull/20485/head
Vadim Levin 3 years ago
parent cff0168f3a
commit 531ea5b3a2
  1. 6
      modules/core/include/opencv2/core/bindings_utils.hpp
  2. 12
      modules/python/src2/gen2.py
  3. 17
      modules/python/test/test_misc.py

@ -116,6 +116,12 @@ String dumpRange(const Range& argument)
}
}
CV_WRAP static inline
String testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3)
{
return format("arg=%d, lambda=%d, from=%d", positional_argument, lambda, from);
}
CV_WRAP static inline
void testRaiseGeneralException()
{

@ -212,6 +212,16 @@ simple_argtype_mapping = {
"c_string": ArgTypeInfo("char*", FormatStrings.string, '(char*)""')
}
# Set of reserved keywords for Python. Can be acquired via the following call
# $ python -c "help('keywords')"
# Keywords that are reserved in C/C++ are excluded because they can not be
# used as variables identifiers
python_reserved_keywords = {
"True", "None", "False", "as", "assert", "def", "del", "elif", "except", "exec",
"finally", "from", "global", "import", "in", "is", "lambda", "nonlocal",
"pass", "print", "raise", "with", "yield"
}
def normalize_class_name(name):
return re.sub(r"^cv\.", "", name).replace(".", "_")
@ -369,6 +379,8 @@ class ArgInfo(object):
def __init__(self, arg_tuple):
self.tp = handle_ptr(arg_tuple[0])
self.name = arg_tuple[1]
if self.name in python_reserved_keywords:
self.name += "_"
self.defval = arg_tuple[2]
self.isarray = False
self.arraylen = 0

@ -463,6 +463,23 @@ class Arguments(NewOpenCVTests):
with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
_ = cv.utils.dumpRange(not_convertible)
def test_reserved_keywords_are_transformed(self):
default_lambda_value = 2
default_from_value = 3
format_str = "arg={}, lambda={}, from={}"
self.assertEqual(
cv.utils.testReservedKeywordConversion(20), format_str.format(20, default_lambda_value, default_from_value)
)
self.assertEqual(
cv.utils.testReservedKeywordConversion(10, lambda_=10), format_str.format(10, 10, default_from_value)
)
self.assertEqual(
cv.utils.testReservedKeywordConversion(10, from_=10), format_str.format(10, default_lambda_value, 10)
)
self.assertEqual(
cv.utils.testReservedKeywordConversion(20, lambda_=-4, from_=12), format_str.format(20, -4, 12)
)
class SamplesFindFile(NewOpenCVTests):

Loading…
Cancel
Save