diff --git a/README.md b/README.md index d72199bc..49eb6217 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,16 @@ Pycall.rb maps the callable attribute of an object to the instance method of the But, unfortunately, this mapping prohibits us to get the callable attributes. We need to write `PyCall.getattr(obj, :meth)` in Ruby to get `obj.meth` object while we can write `obj.meth` in Python. +When no argument is given, pycall.rb calls the attribute only if it is a routine, such as a function, a method, a builtin function, a Cython function, or a `functools.partial` object (roughly what Python's `inspect.isroutine()` accepts). Other callable objects, such as instances of a class that defines `__call__`, are returned without being called. For example, `scipy.stats.norm` is such an object, so the following code works as in Python: + +```ruby +stats = PyCall.import_module('scipy.stats') +stats.norm.pdf([1, 2, 3], 0, 10) # stats.norm is not called here +stats.norm(0, 10).pdf([1, 2, 3]) # stats.norm is called with the given arguments +``` + +To call such an object without arguments, write `obj.attr.()` (or `obj.attr.call`). + ### Specifying the Python version If you want to use a specific version of Python instead of the default, diff --git a/ext/pycall/pycall.c b/ext/pycall/pycall.c index 7f878b72..ed4d4418 100644 --- a/ext/pycall/pycall.c +++ b/ext/pycall/pycall.c @@ -23,6 +23,12 @@ static int python_has_stackless_extension; static PyObject *python_builtins_module; static ID id_python_type_mapping; +/* Types used by pycall_is_python_routine (NULL when not available) */ +static PyTypeObject *python_builtin_function_type; /* builtin_function_or_method */ +static PyTypeObject *python_method_type; /* bound method (instancemethod in Python 2) */ +static PyTypeObject *python_method_wrapper_type; /* method-wrapper */ +static PyTypeObject *python_partial_type; /* functools.partial */ + /* Don't keep Ruby objects that aren't pinned in C global variables. * They may be moved by GC compaction. */ @@ -1191,6 +1197,63 @@ pycall_call_python_callable(PyObject *pycallable, int argc, VALUE *argv) return obj; } +static int +pycall_type_is_subtype(PyTypeObject *type, PyTypeObject *base) +{ + if (!base) + return 0; + for (; type; type = type->tp_base) { + if (type == base) + return 1; + } + return 0; +} + +/* Returns true if pyobj is a function-like routine, i.e. a callable that + * Python's inspect.isroutine() recognizes: + * + * - builtin functions and methods (builtin_function_or_method), + * - bound methods (method), + * - method-wrapper objects, + * - non-data descriptors (types that define __get__ but not __set__), + * which covers Python functions, method descriptors, slot wrappers, + * Cython functions, functools.lru_cache wrappers, numpy's array function + * dispatchers, and so on. + * + * functools.partial is also treated as a routine because it is one since + * Python 3.14 (it gained __get__), and we want the same behavior on older + * Python versions. Ruby's Proc and Method objects wrapped in Python are + * treated as routines, too. + * + * Other callable objects, such as instances of a class defining __call__ + * (e.g. scipy.stats.norm) and numpy ufuncs, are not routines. */ +static int +pycall_is_python_routine(PyObject *pyobj) +{ + PyTypeObject *type = Py_TYPE(pyobj); + + if (pycall_type_is_subtype(type, python_builtin_function_type) || + pycall_type_is_subtype(type, python_method_type) || + pycall_type_is_subtype(type, python_method_wrapper_type)) { + return 1; + } + + if (type->tp_descr_get != NULL && type->tp_descr_set == NULL) { + return 1; + } + + if (pycall_type_is_subtype(type, python_partial_type)) { + return 1; + } + + if (PyRuby_Check(pyobj)) { + VALUE obj = PyRuby_get_ruby_object(pyobj); + return RTEST(rb_obj_is_proc(obj)) || RTEST(rb_obj_is_method(obj)); + } + + return 0; +} + static VALUE pycall_pyobject_wrapper_wrapper_method(int argc, VALUE *argv, VALUE wrapper) { @@ -1243,6 +1306,16 @@ pycall_pyobject_wrapper_wrapper_method(int argc, VALUE *argv, VALUE wrapper) if (PyType_Check(attr) || PyClass_Check(attr)) return pycall_pyobject_to_ruby(attr); + /* Ruby cannot distinguish `obj.attr` from `obj.attr()`. When no argument + * is given, call the attribute only if it is a routine such as a function + * or a method; return other callable objects (e.g. scipy.stats.norm) as + * they are so that `obj.attr.meth(...)` works as in Python. */ + if (argc == 0 && !pycall_is_python_routine(attr)) { + VALUE obj = pycall_pyobject_to_ruby(attr); + pycall_Py_DecRef(attr); + return obj; + } + VALUE obj = pycall_call_python_callable(attr, argc, argv); pycall_Py_DecRef(attr); return obj; @@ -2287,6 +2360,40 @@ pycall_PyObject_DelAttrString(PyObject *pyobj, const char *attr_name) return Py_API(PyObject_SetAttrString)(pyobj, attr_name, NULL); } +/* Returns the type object stored in pyobj.name, or NULL. + * The returned type is kept alive for the process lifetime. */ +static PyTypeObject * +get_python_type_attr(PyObject *pyobj, char const *name) +{ + PyObject *attr = Py_API(PyObject_GetAttrString)(pyobj, name); + if (!attr) { + Py_API(PyErr_Clear)(); + return NULL; + } + if (!PyType_Check(attr)) { + pycall_Py_DecRef(attr); + return NULL; + } + return (PyTypeObject *)attr; +} + +/* Returns the type of pyobj.name, or NULL. + * The returned type is kept alive for the process lifetime. */ +static PyTypeObject * +get_python_type_of_attr(PyObject *pyobj, char const *name) +{ + PyTypeObject *type; + PyObject *attr = Py_API(PyObject_GetAttrString)(pyobj, name); + if (!attr) { + Py_API(PyErr_Clear)(); + return NULL; + } + type = Py_TYPE(attr); + Py_API(Py_IncRef)((PyObject *)type); + pycall_Py_DecRef(attr); + return type; +} + static void init_python(void) { @@ -2332,6 +2439,32 @@ init_python(void) python_hexversion = Py_API(PyLong_AsSsize_t)(hexversion); } + /* types for pycall_is_python_routine */ + + python_builtin_function_type = get_python_type_of_attr(python_builtins_module, "len"); + python_method_wrapper_type = get_python_type_of_attr(Py_API(_Py_NoneStruct), "__repr__"); + { + PyObject *types, *functools; + + types = Py_API(PyImport_ImportModule)("types"); + if (types) { + python_method_type = get_python_type_attr(types, "MethodType"); + pycall_Py_DecRef(types); + } + else { + Py_API(PyErr_Clear)(); + } + + functools = Py_API(PyImport_ImportModule)("functools"); + if (functools) { + python_partial_type = get_python_type_attr(functools, "partial"); + pycall_Py_DecRef(functools); + } + else { + Py_API(PyErr_Clear)(); + } + } + /* constants */ Py_API(Py_IncRef)(Py_API(_Py_NoneStruct)); diff --git a/spec/pycall/callable_attribute_spec.rb b/spec/pycall/callable_attribute_spec.rb new file mode 100644 index 00000000..ea926be0 --- /dev/null +++ b/spec/pycall/callable_attribute_spec.rb @@ -0,0 +1,94 @@ +require 'spec_helper' + +# GitHub issue #87: Ruby cannot distinguish `obj.attr` from `obj.attr()`. +# When no argument is given, a callable attribute is called only if it is a +# routine (function, method, etc.). Other callable objects are returned as +# they are. +RSpec.describe 'callable attributes of Python objects' do + let(:mod) { PyCall.import_module('pycall.callable_attribute') } + + context 'when the attribute is a callable instance (like scipy.stats.norm)' do + it 'returns the object itself when no argument is given' do + norm = mod.norm + expect(norm).to be_a(PyCall::PyObjectWrapper) + expect(norm).to be_kind_of(mod.DistributionGenerator) + end + + it 'allows calling a method of the object with all its arguments' do + expect(mod.norm.pdf([1, 2, 3], 0, 10)).to eq('generator pdf([1, 2, 3]) loc=0 scale=10') + end + + it 'calls the object when arguments are given' do + frozen = mod.norm(0, 10) + expect(frozen).to be_kind_of(mod.FrozenDistribution) + expect(frozen.pdf(5)).to eq('frozen pdf(5) loc=0 scale=10') + end + + it 'calls the object when only keyword arguments are given' do + frozen = mod.norm(loc: 1, scale: 2) + expect(frozen.pdf(5)).to eq('frozen pdf(5) loc=1 scale=2') + end + + it 'calls the object by #call' do + frozen = mod.norm.() + expect(frozen.pdf(5)).to eq('frozen pdf(5) loc=0 scale=1') + end + + it 'returns the object from a class attribute and an instance attribute' do + target = mod.Target.new + expect(mod.Target.norm.pdf(1, 2, 3)).to eq('generator pdf(1) loc=2 scale=3') + expect(target.norm.pdf(1, 2, 3)).to eq('generator pdf(1) loc=2 scale=3') + expect(target.instance_norm.pdf(1, 2, 3)).to eq('generator pdf(1) loc=2 scale=3') + end + end + + context 'when the attribute is a routine' do + it 'calls a module-level function without arguments' do + expect(mod.zero_arg_function).to eq('function called') + end + + it 'calls a bound method without arguments' do + expect(mod.Target.new.zero_arg_method).to eq('method called') + end + + it 'calls a staticmethod without arguments' do + expect(mod.Target.zero_arg_staticmethod).to eq('staticmethod called') + expect(mod.Target.new.zero_arg_staticmethod).to eq('staticmethod called') + end + + it 'calls a classmethod without arguments' do + expect(mod.Target.zero_arg_classmethod).to eq('classmethod called on Target') + expect(mod.Target.new.zero_arg_classmethod).to eq('classmethod called on Target') + end + + it 'calls a builtin method without arguments' do + expect(mod.builtin_method).to eq('ABC') + end + + it 'calls a builtin function without arguments' do + expect(PyCall.import_module('os').getpid).to eq(Process.pid) + end + + it 'calls a method-wrapper without arguments' do + expect(mod.method_wrapper).to eq('42') + end + + it 'calls a functools.lru_cache wrapper without arguments' do + expect(mod.cached_zero_arg_function).to eq('cached function called') + end + + it 'calls a functools.partial object without arguments' do + expect(mod.partial_function).to eq('partial called with 42') + end + + it 'calls a callable non-data descriptor without arguments' do + expect(mod.descriptor_callable).to eq('descriptor called') + end + + it 'calls a Ruby lambda stored in a Python attribute without arguments' do + target = mod.Target.new + PyCall.setattr(target, :callback, -> { 'ruby lambda called' }) + expect(target.callback).to eq('ruby lambda called') + end + end +end diff --git a/spec/python/pycall/callable_attribute.py b/spec/python/pycall/callable_attribute.py new file mode 100644 index 00000000..708e27a4 --- /dev/null +++ b/spec/python/pycall/callable_attribute.py @@ -0,0 +1,74 @@ +"""Helpers for the specs of callable attributes (GitHub issue #87).""" + +import functools + + +class FrozenDistribution(object): + def __init__(self, loc, scale): + self.loc = loc + self.scale = scale + + def pdf(self, x): + return 'frozen pdf(%r) loc=%r scale=%r' % (x, self.loc, self.scale) + + +class DistributionGenerator(object): + """Mimics scipy.stats.rv_continuous: a callable instance whose __call__ + returns a frozen distribution with fixed parameters.""" + + def __call__(self, loc=0, scale=1): + return FrozenDistribution(loc, scale) + + def pdf(self, x, loc=0, scale=1): + return 'generator pdf(%r) loc=%r scale=%r' % (x, loc, scale) + + +# Like scipy.stats.norm +norm = DistributionGenerator() + + +def zero_arg_function(): + return 'function called' + + +@functools.lru_cache(maxsize=None) +def cached_zero_arg_function(): + return 'cached function called' + + +partial_function = functools.partial(lambda x: 'partial called with %s' % x, 42) + +builtin_method = 'abc'.upper + +method_wrapper = (42).__repr__ + + +class DescriptorCallable(object): + """A callable non-data descriptor, which inspect.isroutine() accepts.""" + + def __get__(self, obj, objtype=None): + return self + + def __call__(self): + return 'descriptor called' + + +descriptor_callable = DescriptorCallable() + + +class Target(object): + norm = norm + + def __init__(self): + self.instance_norm = DistributionGenerator() + + def zero_arg_method(self): + return 'method called' + + @staticmethod + def zero_arg_staticmethod(): + return 'staticmethod called' + + @classmethod + def zero_arg_classmethod(cls): + return 'classmethod called on %s' % cls.__name__