Get method's class name in a python3-compatible way

This way of getting an instance method's class name does not rely on
the im_class attribute and is compatible with any version of python
after 2.7

Co-Authored-By: David Stanek <dstanek@dstanek.com>
Change-Id: I7fffa2ec3c5fd68b8d36324ded6f58f26a93d419
Closes-Bug: 1418643
This commit is contained in:
Matthieu Huin 2015-02-24 17:29:21 +01:00 committed by David Stanek
parent 53237b5d9b
commit dbb98ef7db
2 changed files with 9 additions and 8 deletions

View File

@ -242,19 +242,20 @@ def internal(*args, **kwargs):
def _get_callback_info(callback):
"""Return list containing callback's module and name.
If the callback is an instance method also return the class name.
If the callback is a bound instance method also return the class name.
:param callback: Function to call
:type callback: function
:returns: List containing parent module, (optional class,) function name
:rtype: list
"""
if getattr(callback, 'im_class', None):
return [getattr(callback, '__module__', None),
callback.im_class.__name__,
callback.__name__]
module_name = getattr(callback, '__module__', None)
func_name = callback.__name__
if inspect.ismethod(callback):
class_name = callback.__self__.__class__.__name__
return [module_name, class_name, func_name]
else:
return [getattr(callback, '__module__', None), callback.__name__]
return [module_name, func_name]
def register_event_callback(event, resource_type, callbacks):

View File

@ -1007,7 +1007,7 @@ class TestCallbackRegistration(unit.BaseTestCase):
with mock.patch('keystone.notifications.LOG', self.mock_log):
notifications.register_event_callback(
CREATED_OPERATION, 'thing', C.callback)
CREATED_OPERATION, 'thing', C().callback)
callback = 'keystone.tests.unit.common.test_notifications.C.callback'
expected_log_data = {
@ -1026,7 +1026,7 @@ class TestCallbackRegistration(unit.BaseTestCase):
with mock.patch('keystone.notifications.LOG', self.mock_log):
notifications.register_event_callback(
CREATED_OPERATION, 'thing', [callback, C.callback])
CREATED_OPERATION, 'thing', [callback, C().callback])
callback_1 = 'keystone.tests.unit.common.test_notifications.callback'
callback_2 = 'keystone.tests.unit.common.test_notifications.C.callback'