Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New utility: is_bound_method #342

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions six.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,9 @@ def callable(obj):


if PY3:
def is_bound_method(func):
return callable(func) and hasattr(func, _meth_self)

def get_unbound_function(unbound):
return unbound

Expand All @@ -551,6 +554,15 @@ def create_unbound_method(func, cls):

Iterator = object
else:
_builtin_bound_method_type = type((0).bit_length)
_method_wrapper_type = type((0).__abs__)

def is_bound_method(func):
return (
callable(func) and getattr(func, _meth_self, None) is not None
or isinstance(func, (_builtin_bound_method_type, _method_wrapper_type))
)

def get_unbound_function(unbound):
return unbound.im_func

Expand Down
51 changes: 51 additions & 0 deletions test_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,57 @@ def f(self):
assert f(x) is x


class TestIsBoundMethod:
class DummyClass:
@staticmethod
def static():
pass

@classmethod
def class_meth(cls):
pass

def meth(self):
pass

def a_free_function(self):
pass

@pytest.mark.parametrize(
"meth",
[
DummyClass().meth,
DummyClass.class_meth,
DummyClass().class_meth,
(0).bit_length,
"".join,
"foo".__lt__,
(0).__abs__,
]
)
def test_is_bound_method_true(self, meth):
assert six.is_bound_method(meth)

@pytest.mark.parametrize(
"obj",
[
lambda x: x,
a_free_function,
DummyClass.meth,
DummyClass.static,
DummyClass().static,
int.bit_length,
str.join,
str.__lt__,
]
)
def test_is_bound_method_false(self, obj):
assert not six.is_bound_method(obj)

del DummyClass
del a_free_function


if six.PY3:

def test_b():
Expand Down