Python six.get_method_function() Examples

The following are 17 code examples for showing how to use six.get_method_function(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module six , or try the search function .

Example 1
Project: python-esppy   Author: sassoftware   File: config.py    License: Apache License 2.0 6 votes vote down vote up
def subscribe(func):
    '''
    Add a subscriber function to option events

    Parameters
    ----------
    func : callable
        A callable object that takes two parameters: key and value.
        This function is called with the name and value of any option
        that is set.

    Returns
    -------
    None

    '''
    if isinstance(func, types.MethodType):
        obj = six.get_method_self(func)
        func = six.get_method_function(func)
        _subscribers[func] = (weakref.ref(func), weakref.ref(obj))
    else:
        _subscribers[func] = (weakref.ref(func), None) 
Example 2
Project: easy_cache   Author: Bahus   File: decorators.py    License: MIT License 6 votes vote down vote up
def wrapper(self):
        if not self._wrapped:
            if self._instance or self._class:
                wrapped = self._func.__get__(self._instance, self._class)

                if isinstance(self._func, staticmethod):
                    # we don't need instance or class, however we need scope
                    self.cache.scope = self._instance or self._class
                    self._instance = None
                    self._class = None
                else:
                    wrapped = six.get_method_function(wrapped)
            else:
                wrapped = self._func

            update_wrapper(self.cache, wrapped)
            self.cache.function = wrapped
            self.cache.instance = self._instance
            self.cache.klass = self._class
            self._wrapped = True

        return self.cache 
Example 3
Project: knack   Author: microsoft   File: commands.py    License: MIT License 5 votes vote down vote up
def _get_op_handler(operation):
        """ Import and load the operation handler """
        try:
            mod_to_import, attr_path = operation.split('#')
            op = import_module(mod_to_import)
            for part in attr_path.split('.'):
                op = getattr(op, part)
            if isinstance(op, types.FunctionType):
                return op
            return six.get_method_function(op)
        except (ValueError, AttributeError):
            raise ValueError("The operation '{}' is invalid.".format(operation)) 
Example 4
Project: fetchman   Author: DarkSand   File: reqser.py    License: Apache License 2.0 5 votes vote down vote up
def _find_method(obj, func):
    if obj:
        try:
            func_self = six.get_method_self(func)
        except AttributeError:  # func has no __self__
            pass
        else:
            if func_self is obj:
                return six.get_method_function(func).__name__
    raise ValueError("Function %s is not a method of: %s" % (func, obj)) 
Example 5
Project: Sasila   Author: DarkSand   File: reqser.py    License: Apache License 2.0 5 votes vote down vote up
def _find_method(obj, func):
    if obj:
        try:
            func_self = six.get_method_self(func)
        except AttributeError:  # func has no __self__
            pass
        else:
            if func_self is obj:
                return six.get_method_function(func).__name__
    raise ValueError("Function %s is not a method of: %s" % (func, obj)) 
Example 6
Project: learn_python3_spider   Author: wistbean   File: reqser.py    License: MIT License 5 votes vote down vote up
def _find_method(obj, func):
    if obj:
        try:
            func_self = six.get_method_self(func)
        except AttributeError:  # func has no __self__
            pass
        else:
            if func_self is obj:
                name = six.get_method_function(func).__name__
                if _is_private_method(name):
                    return _mangle_private_name(obj, func, name)
                return name
    raise ValueError("Function %s is not a method of: %s" % (func, obj)) 
Example 7
Project: learn_python3_spider   Author: wistbean   File: reqser.py    License: MIT License 5 votes vote down vote up
def _find_method(obj, func):
    if obj:
        try:
            func_self = six.get_method_self(func)
        except AttributeError:  # func has no __self__
            pass
        else:
            if func_self is obj:
                name = six.get_method_function(func).__name__
                if _is_private_method(name):
                    return _mangle_private_name(obj, func, name)
                return name
    raise ValueError("Function %s is not a method of: %s" % (func, obj)) 
Example 8
Project: pytest-localstack   Author: mintel   File: utils.py    License: MIT License 5 votes vote down vote up
def unbind(func):
    """Get Function from Method (if not already Function)."""
    if isinstance(func, types.MethodType):
        func = six.get_method_function(func)
    return func 
Example 9
Project: six   Author: benjaminp   File: test_six.py    License: MIT License 5 votes vote down vote up
def test_get_method_function():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_function(x.m) is X.__dict__["m"]
    pytest.raises(AttributeError, six.get_method_function, hasattr) 
Example 10
Project: dotty   Author: google   File: dispatch.py    License: Apache License 2.0 5 votes vote down vote up
def __get_unbound_function(method):
        try:
            return six.get_method_function(method)
        except AttributeError:
            return method 
Example 11
Project: c4ddev   Author: NiklasRosenstein   File: test_six.py    License: MIT License 5 votes vote down vote up
def test_get_method_function():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_function(x.m) is X.__dict__["m"]
    py.test.raises(AttributeError, six.get_method_function, hasattr) 
Example 12
Project: fabricio   Author: renskiy   File: tasks.py    License: MIT License 5 votes vote down vote up
def __details__(self):
            with utils.patch(
                six.get_method_function(self.tasks.service.destroy),
                '__doc__',
                self.__doc__ + (self.tasks.service.destroy.__doc__ or ''),
            ):
                return get_task_details(self.tasks.service.destroy) 
Example 13
Project: data   Author: jmankoff   File: test_six.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_get_method_function():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_function(x.m) is X.__dict__["m"]
    py.test.raises(AttributeError, six.get_method_function, hasattr) 
Example 14
Project: data   Author: jmankoff   File: test_six.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_get_method_function():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_function(x.m) is X.__dict__["m"]
    py.test.raises(AttributeError, six.get_method_function, hasattr) 
Example 15
Project: linter-pylama   Author: AtomLinter   File: raw_building.py    License: MIT License 4 votes vote down vote up
def object_build(self, node, obj):
        """recursive method which create a partial ast from real objects
         (only function, class, and method are handled)
        """
        if obj in self._done:
            return self._done[obj]
        self._done[obj] = node
        for name in dir(obj):
            try:
                member = getattr(obj, name)
            except AttributeError:
                # damned ExtensionClass.Base, I know you're there !
                attach_dummy_node(node, name)
                continue
            if inspect.ismethod(member):
                member = six.get_method_function(member)
            if inspect.isfunction(member):
                _build_from_function(node, name, member, self._module)
            elif inspect.isbuiltin(member):
                if (not _io_discrepancy(member) and
                        self.imported_member(node, member, name)):
                    continue
                object_build_methoddescriptor(node, member, name)
            elif inspect.isclass(member):
                if self.imported_member(node, member, name):
                    continue
                if member in self._done:
                    class_node = self._done[member]
                    if class_node not in node.locals.get(name, ()):
                        node.add_local_node(class_node, name)
                else:
                    class_node = object_build_class(node, member, name)
                    # recursion
                    self.object_build(class_node, member)
                if name == '__class__' and class_node.parent is None:
                    class_node.parent = self._done[self._module]
            elif inspect.ismethoddescriptor(member):
                assert isinstance(member, object)
                object_build_methoddescriptor(node, member, name)
            elif inspect.isdatadescriptor(member):
                assert isinstance(member, object)
                object_build_datadescriptor(node, member, name)
            elif isinstance(member, _CONSTANTS):
                attach_const_node(node, name, member)
            elif inspect.isroutine(member):
                # This should be called for Jython, where some builtin
                # methods aren't caught by isbuiltin branch.
                _build_from_function(node, name, member, self._module)
            else:
                # create an empty node so that the name is actually defined
                attach_dummy_node(node, name, member)
        return None 
Example 16
def _get_observer_key_value(observer):
        """
        Subscribing methods of objects is tricky::

            class TheObserver(object):
                def __init__(self):
                    self.received_data = []

                def on_new_data(self, data):
                    self.received_data.append(data)

            observer1 = TheObserver()
            observer2 = TheObserver()

            subscribe(observer1.on_new_data)
            subscribe(observer2.on_new_data)
            subscribe(observer2.on_new_data)

        Even if it looks like 2 different subscriptions they all
        pass 3 different bound-method objects (different id()).
        So, to differentiate them we need to "unwind" out of them:
        1) self                      - 2 different id()
        2) function object of class  - all 3 have same id()

        Observer key is pair: (self-id, function-id)
        """
        try:
            self_or_none = six.get_method_self(observer)
            self_id = instance_id(self_or_none)
            self_or_none = weakref.proxy(self_or_none)
        except AttributeError:
            self_id = 0  # default for not bound methods
            self_or_none = None

        try:
            func = six.get_method_function(observer)
        except AttributeError:
            func = observer
        function_id = instance_id(func)

        observer_key = (self_id, function_id)
        observer_value = (self_or_none, weakref.proxy(func))
        return observer_key, observer_value 
Example 17
Project: moler   Author: nokia   File: publisher.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _get_subscriber_key_and_value(subscriber):
        """
        Allow Subscribers to be garbage collected while still subscribed inside Publisher

        Subscribing methods of objects is tricky::

            class TheObserver(object):
                def __init__(self):
                    self.received_data = []

                def on_new_data(self, data):
                    self.received_data.append(data)

            observer1 = TheObserver()
            observer2 = TheObserver()

            subscribe(observer1.on_new_data)
            subscribe(observer2.on_new_data)
            subscribe(observer2.on_new_data)

        Even if it looks like 2 different subscriptions they all
        pass 3 different bound-method objects (different id()).
        This is so since access via observer1.on_new_data
        creates new object (bound method) on the fly.

        We want to use weakref but weakref to bound method doesn't work
        see: http://code.activestate.com/recipes/81253/
        and : https://stackoverflow.com/questions/599430/why-doesnt-the-weakref-work-on-this-bound-method
        When we wrap bound-method into weakref it may quickly disappear
        if that is only reference to bound method.
        So, we need to unbind it to have access to real method + self instance

        Unbinding above 3 examples of on_new_data will give:
        1) self                      - 2 different id()
        2) function object of class  - all 3 have same id()

        Observer key is pair: (self-id, function-id)
        """
        try:
            self_or_none = six.get_method_self(subscriber)
            self_id = instance_id(self_or_none)
            self_or_none = weakref.proxy(self_or_none)
        except AttributeError:
            self_id = 0  # default for not bound methods
            self_or_none = None

        try:
            func = six.get_method_function(subscriber)
        except AttributeError:
            func = subscriber
        function_id = instance_id(func)

        subscription_key = (self_id, function_id)
        subscription_value = (self_or_none, weakref.proxy(func))
        return subscription_key, subscription_value