changeset 191:0500459a739b

Enforce checking of attributes in builtins for pycall (fixes issue #20) * pycall.cc: Add the checks to search for an attribute in __main__ and if not found then revert to __builtin__ or builtins depending on python version. Also add a test to demonstrate this
author Abhinav Tripathi <genuinelucifer@gmail.com>
date Tue, 05 Jul 2016 12:00:15 -0700
parents ac377ace2ee4
children 9077907490d8
files pycall.cc
diffstat 1 files changed, 22 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/pycall.cc	Thu Jun 09 14:52:06 2016 -0700
+++ b/pycall.cc	Tue Jul 05 12:00:15 2016 -0700
@@ -89,8 +89,27 @@
       object main_module = import ("__main__");
       object main_namespace = main_module.attr ("__dict__");
 
-      object mod = (module.empty ()) ? main_module : import (module.c_str ());
-      object callable = mod.attr (func.c_str ());
+      object mod, callable;
+
+      if (! module.empty ())
+        {
+          mod = import (module.c_str ());
+        }
+      if (! PyObject_HasAttrString (mod.ptr (), func.c_str ()))
+        {
+          if (! PyObject_HasAttrString (main_module.ptr (), func.c_str ()))
+            {
+#if PY_VERSION_HEX >= 0x03000000
+	      mod = import ("builtins");
+#else
+	      mod = import ("__builtin__");
+#endif
+            }
+          else
+            mod = main_module;
+        }
+
+      callable = mod.attr (func.c_str ());
 
       std::vector<object> pyargs;
       for (int i = 1; i < nargin; i++)
@@ -188,6 +207,7 @@
 %!xtest assert (pycall ("math.trunc", pi), fix (pi))
 %!assert (pycall ("math.sqrt", 2), sqrt (2))
 %!xtest assert (pycall ("cmath.sqrt", 2j), sqrt (2j))
+%!assert (pycall ("int", 10.2), 10)
 
 ## Test argument type conversion of values into Python
 %!test