Python six.get_method_self() Examples

The following are 25 code examples of six.get_method_self(). 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 also want to check out all available functions/classes of the module six , or try the search function .
Example #1
Source File: flow.py    From rotest with MIT License 6 votes vote down vote up
def jump_to(self, index):
        """Immediately jump to the start of the block at the given index.

        Args:
            index (number): block index to run.
        """
        self._run_index = index

        tracer = sys.gettrace()
        if tracer:
            debugger = six.get_method_self(tracer)

            def raise_jump(*_args):
                raise JumpException(self)

            debugger.postcmd = lambda *args: True
            debugger.do_continue(None)
            sys.settrace(raise_jump)

        else:
            raise JumpException(self) 
Example #2
Source File: reflection.py    From oslo.utils with Apache License 2.0 6 votes vote down vote up
def is_same_callback(callback1, callback2, strict=True):
    """Returns if the two callbacks are the same."""
    if callback1 is callback2:
        # This happens when plain methods are given (or static/non-bound
        # methods).
        return True
    if callback1 == callback2:
        if not strict:
            return True
        # Two bound methods are equal if functions themselves are equal and
        # objects they are applied to are equal. This means that a bound
        # method could be the same bound method on another object if the
        # objects have __eq__ methods that return true (when in fact it is a
        # different bound method). Python u so crazy!
        try:
            self1 = six.get_method_self(callback1)
            self2 = six.get_method_self(callback2)
            return self1 is self2
        except AttributeError:  # nosec
            pass
    return False 
Example #3
Source File: config.py    From python-esppy with 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 #4
Source File: __init__.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_bound_method(ob):
    return inspect.ismethod(ob) and six.get_method_self(ob) is not None 
Example #5
Source File: utils.py    From easy_cache with MIT License 5 votes vote down vote up
def get_function_path(function, bound_to=None):
    """Get received function path (as string), to import function later
    with `import_string`.
    """
    if isinstance(function, six.string_types):
        return function

    # static and class methods
    if hasattr(function, '__func__'):
        real_function = function.__func__
    elif callable(function):
        real_function = function
    else:
        return function

    func_path = []

    module = getattr(real_function, '__module__', '__main__')
    if module:
        func_path.append(module)

    if not bound_to:
        try:
            bound_to = six.get_method_self(function)
        except AttributeError:
            pass

    if bound_to:
        if isinstance(bound_to, six.class_types):
            func_path.append(bound_to.__name__)
        else:
            func_path.append(bound_to.__class__.__name__)
        func_path.append(real_function.__name__)
    else:
        # qualname is available in Python 3 only
        func_path.append(getattr(real_function, '__qualname__', real_function.__name__))

    return '.'.join(func_path) 
Example #6
Source File: reflection.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def is_bound_method(method):
    """Returns if the given method is bound to an object."""
    return get_method_self(method) is not None 
Example #7
Source File: reflection.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def get_method_self(method):
    """Gets the ``self`` object attached to this method (or none)."""
    if not inspect.ismethod(method):
        return None
    try:
        return six.get_method_self(method)
    except AttributeError:
        return None 
Example #8
Source File: reflection.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def get_callable_name(function):
    """Generate a name from callable.

    Tries to do the best to guess fully qualified callable name.
    """
    method_self = get_method_self(function)
    if method_self is not None:
        # This is a bound method.
        if isinstance(method_self, six.class_types):
            # This is a bound class method.
            im_class = method_self
        else:
            im_class = type(method_self)
        try:
            parts = (im_class.__module__, function.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__, function.__name__)
    elif inspect.ismethod(function) or inspect.isfunction(function):
        # This could be a function, a static method, a unbound method...
        try:
            parts = (function.__module__, function.__qualname__)
        except AttributeError:
            if hasattr(function, 'im_class'):
                # This is a unbound method, which exists only in python 2.x
                im_class = function.im_class
                parts = (im_class.__module__,
                         im_class.__name__, function.__name__)
            else:
                parts = (function.__module__, function.__name__)
    else:
        im_class = type(function)
        if im_class is _TYPE_TYPE:
            im_class = function
        try:
            parts = (im_class.__module__, im_class.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__)
    return '.'.join(parts) 
Example #9
Source File: reflection.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def get_class_name(obj, fully_qualified=True, truncate_builtins=True):
    """Get class name for object.

    If object is a type, returns name of the type. If object is a bound
    method or a class method, returns its ``self`` object's class name.
    If object is an instance of class, returns instance's class name.
    Else, name of the type of the object is returned. If fully_qualified
    is True, returns fully qualified name of the type. For builtin types,
    just name is returned. TypeError is raised if can't get class name from
    object.
    """
    if inspect.isfunction(obj):
        raise TypeError("Can't get class name.")

    if inspect.ismethod(obj):
        obj = get_method_self(obj)
    if not isinstance(obj, six.class_types):
        obj = type(obj)
    if truncate_builtins:
        try:
            built_in = obj.__module__ in _BUILTIN_MODULES
        except AttributeError:  # nosec
            pass
        else:
            if built_in:
                return obj.__name__
    if fully_qualified and hasattr(obj, '__module__'):
        return '%s.%s' % (obj.__module__, obj.__name__)
    else:
        return obj.__name__ 
Example #10
Source File: test_six.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_get_method_self():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_self(x.m) is x
    py.test.raises(AttributeError, six.get_method_self, 42) 
Example #11
Source File: test_six.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_get_method_self():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_self(x.m) is x
    py.test.raises(AttributeError, six.get_method_self, 42) 
Example #12
Source File: test_six.py    From c4ddev with MIT License 5 votes vote down vote up
def test_get_method_self():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_self(x.m) is x
    py.test.raises(AttributeError, six.get_method_self, 42) 
Example #13
Source File: secure.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_security(controller, im_self=None):
    """ Checks the security of a controller.  """
    if controller._pecan.get('secured', False):
        check_permissions = controller._pecan['check_permissions']

        if isinstance(check_permissions, six.string_types):
            check_permissions = getattr(
                im_self or six.get_method_self(controller),
                check_permissions
            )

        if not check_permissions():
            raise exc.HTTPUnauthorized 
Example #14
Source File: secure.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __set_parent(self, parent):
        if ismethod(parent):
            self._parent = six.get_method_self(parent)
        else:
            self._parent = parent 
Example #15
Source File: test_six.py    From six with MIT License 5 votes vote down vote up
def test_get_method_self():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_self(x.m) is x
    pytest.raises(AttributeError, six.get_method_self, 42) 
Example #16
Source File: reqser.py    From learn_python3_spider with 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 #17
Source File: reqser.py    From learn_python3_spider with 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 #18
Source File: reqser.py    From Sasila with 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 #19
Source File: _utils.py    From debtcollector with Apache License 2.0 5 votes vote down vote up
def get_method_self(method):
    """Gets the ``self`` object attached to this method (or none)."""
    if not inspect.ismethod(method):
        return None
    try:
        return six.get_method_self(method)
    except AttributeError:
        return None 
Example #20
Source File: reqser.py    From fetchman with 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 #21
Source File: middleware.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def download(self, download_func, request, spider):
        @defer.inlineCallbacks
        def process_request(request):
            for method in self.methods['process_request']:
                response = yield method(request=request, spider=spider)
                if response is not None and not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_request must return None, Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, response.__class__.__name__))
                if response:
                    defer.returnValue(response)
            defer.returnValue((yield download_func(request=request, spider=spider)))

        @defer.inlineCallbacks
        def process_response(response):
            assert response is not None, 'Received None in process_response'
            if isinstance(response, Request):
                defer.returnValue(response)

            for method in self.methods['process_response']:
                response = yield method(request=request, response=response, spider=spider)
                if not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_response must return Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, type(response)))
                if isinstance(response, Request):
                    defer.returnValue(response)
            defer.returnValue(response)

        @defer.inlineCallbacks
        def process_exception(_failure):
            exception = _failure.value
            for method in self.methods['process_exception']:
                response = yield method(request=request, exception=exception, spider=spider)
                if response is not None and not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_exception must return None, Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, type(response)))
                if response:
                    defer.returnValue(response)
            defer.returnValue(_failure)

        deferred = mustbe_deferred(process_request, request)
        deferred.addErrback(process_exception)
        deferred.addCallback(process_response)
        return deferred 
Example #22
Source File: middleware.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def download(self, download_func, request, spider):
        @defer.inlineCallbacks
        def process_request(request):
            for method in self.methods['process_request']:
                response = yield method(request=request, spider=spider)
                if response is not None and not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_request must return None, Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, response.__class__.__name__))
                if response:
                    defer.returnValue(response)
            defer.returnValue((yield download_func(request=request, spider=spider)))

        @defer.inlineCallbacks
        def process_response(response):
            assert response is not None, 'Received None in process_response'
            if isinstance(response, Request):
                defer.returnValue(response)

            for method in self.methods['process_response']:
                response = yield method(request=request, response=response, spider=spider)
                if not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_response must return Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, type(response)))
                if isinstance(response, Request):
                    defer.returnValue(response)
            defer.returnValue(response)

        @defer.inlineCallbacks
        def process_exception(_failure):
            exception = _failure.value
            for method in self.methods['process_exception']:
                response = yield method(request=request, exception=exception, spider=spider)
                if response is not None and not isinstance(response, (Response, Request)):
                    raise _InvalidOutput('Middleware %s.process_exception must return None, Response or Request, got %s' % \
                                         (six.get_method_self(method).__class__.__name__, type(response)))
                if response:
                    defer.returnValue(response)
            defer.returnValue(_failure)

        deferred = mustbe_deferred(process_request, request)
        deferred.addErrback(process_exception)
        deferred.addCallback(process_response)
        return deferred 
Example #23
Source File: _utils.py    From debtcollector with Apache License 2.0 4 votes vote down vote up
def get_callable_name(function):
    """Generate a name from callable.

    Tries to do the best to guess fully qualified callable name.
    """
    method_self = get_method_self(function)
    if method_self is not None:
        # This is a bound method.
        if isinstance(method_self, six.class_types):
            # This is a bound class method.
            im_class = method_self
        else:
            im_class = type(method_self)
        try:
            parts = (im_class.__module__, function.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__, function.__name__)
    elif inspect.ismethod(function) or inspect.isfunction(function):
        # This could be a function, a static method, a unbound method...
        try:
            parts = (function.__module__, function.__qualname__)
        except AttributeError:
            if hasattr(function, 'im_class'):
                # This is a unbound method, which exists only in python 2.x
                im_class = function.im_class
                parts = (im_class.__module__,
                         im_class.__name__, function.__name__)
            else:
                parts = (function.__module__, function.__name__)
    else:
        im_class = type(function)
        if im_class is _TYPE_TYPE:
            im_class = function
        try:
            parts = (im_class.__module__, im_class.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__)
    # When running under sphinx it appears this can be none? if so just
    # don't include it...
    mod, rest = (parts[0], parts[1:])
    if not mod:
        return '.'.join(rest)
    else:
        return '.'.join(parts) 
Example #24
Source File: publisher.py    From moler with 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 
Example #25
Source File: threaded_moler_connection.py    From moler with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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