From a0a8b9890a821bb56aace86ed18e57b2a1137e07 Mon Sep 17 00:00:00 2001 From: Ryan P Kilby Date: Thu, 22 Sep 2016 13:56:27 -0400 Subject: [PATCH] Add py3k compatibility to is_simple_callable --- rest_framework/fields.py | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 917a151e5..7f8391b8a 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -49,20 +49,34 @@ class empty: pass -def is_simple_callable(obj): - """ - True if the object is a callable that takes no arguments. - """ - function = inspect.isfunction(obj) - method = inspect.ismethod(obj) +if six.PY3: + def is_simple_callable(obj): + """ + True if the object is a callable that takes no arguments. + """ + if not callable(obj): + return False - if not (function or method): - return False + sig = inspect.signature(obj) + params = sig.parameters.values() + return all(param.default != param.empty for param in params) - args, _, _, defaults = inspect.getargspec(obj) - len_args = len(args) if function else len(args) - 1 - len_defaults = len(defaults) if defaults else 0 - return len_args <= len_defaults +else: + def is_simple_callable(obj): + function = inspect.isfunction(obj) + method = inspect.ismethod(obj) + + if not (function or method): + return False + + if method: + is_unbound = obj.im_self is None + + args, _, _, defaults = inspect.getargspec(obj) + + len_args = len(args) if function or is_unbound else len(args) - 1 + len_defaults = len(defaults) if defaults else 0 + return len_args <= len_defaults def get_attribute(instance, attrs):