Python types.MethodType() Examples

The following are code examples for showing how to use types.MethodType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_funcattrs.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_im_func_non_method(self):
        # Behavior should be the same when a method is added via an attr
        # assignment
        self.f.id = types.MethodType(id, None, self.f)
        self.assertEqual(self.fi.id(), id(self.fi))
        self.assertNotEqual(self.fi.id(), id(self.f))
        # Test usage
        try:
            self.f.id.unknown_attr
        except AttributeError:
            pass
        else:
            self.fail("using unknown attributes should raise AttributeError")
        # Test assignment and deletion
        self.cannot_set_attr(self.f.id, 'unknown_attr', 2, AttributeError)
        self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_calltips.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_builtins(self):
        # 2.7 puts '()\n' where 3.x does not, other minor differences

        # Python class that inherits builtin methods
        class List(list): "List() doc"
        # Simulate builtin with no docstring for default argspec test
        class SB:  __call__ = None

        def gtest(obj, out):
            self.assertEqual(signature(obj), out)

        gtest(List, '()\n' + List.__doc__)
        gtest(list.__new__,
               'T.__new__(S, ...) -> a new object with type S, a subtype of T')
        gtest(list.__init__,
               'x.__init__(...) initializes x; see help(type(x)) for signature')
        append_doc =  "L.append(object) -- append object to end"
        gtest(list.append, append_doc)
        gtest([].append, append_doc)
        gtest(List.append, append_doc)

        gtest(types.MethodType, '()\ninstancemethod(function, instance, class)')
        gtest(SB(), default_tip) 
Example 3
Project: mlimages   Author: icoxfog417   File: log_api.py    MIT License 6 votes vote down vote up
def create_file_logger(root, name, file_name="log.txt", timestamp_format="", debug=False):
    file_api = FileAPI(root)
    timestamp = ""
    if timestamp_format:
        timestamp = datetime.now().strftime(timestamp_format)
    else:
        timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

    folder = name + "_" + timestamp
    # prepare folder and file
    with file_api.open_with_mkdir(folder + "/" + file_name) as f:
        f.write("".encode("utf-8"))

    log_root = os.path.join(root, folder)
    logger = create_logger(name, debug)
    fh = FileHandler(os.path.join(log_root, file_name), encoding="utf-8")
    fh.setLevel(_bool_2_level(debug))
    logger.addHandler(fh)

    # add close method to release resource
    logger.close = types.MethodType(__close, logger)
    return logger, log_root 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: runtime.py    MIT License 6 votes vote down vote up
def __init__(self, environment, parent, name, blocks):
        self.parent = parent
        self.vars = {}
        self.environment = environment
        self.eval_ctx = EvalContext(self.environment, name)
        self.exported_vars = set()
        self.name = name

        # create the initial mapping of blocks.  Whenever template inheritance
        # takes place the runtime will update this mapping with the new blocks
        # from the template.
        self.blocks = dict((k, [v]) for k, v in iteritems(blocks))

        # In case we detect the fast resolve mode we can set up an alias
        # here that bypasses the legacy code logic.
        if self._fast_resolve_mode:
            self.resolve_or_missing = MethodType(resolve_or_missing, self) 
Example 5
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self) 
Example 6
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = _OrderedDict()

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.popitem(False)

                def clear(self):
                    cache.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self) 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()
                
            def cache_len(self):
                return len(cache)

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self)
            self.__len__ = types.MethodType(cache_len, self) 
Example 8
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self) 
Example 9
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = _OrderedDict()

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.popitem(False)

                def clear(self):
                    cache.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self) 
Example 10
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 11
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = _OrderedDict()

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.popitem(False)

                def clear(self):
                    cache.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self) 
Example 12
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 13
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()
                
            def cache_len(self):
                return len(cache)

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self)
            self.__len__ = types.MethodType(cache_len, self) 
Example 14
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()
                
            def cache_len(self):
                return len(cache)

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self)
            self.__len__ = types.MethodType(cache_len, self) 
Example 15
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self):
            cache = {}
            self.not_in_cache = not_in_cache = object()

            def get(self, key):
                return cache.get(key, not_in_cache)

            def set(self, key, value):
                cache[key] = value

            def clear(self):
                cache.clear()

            self.get = types.MethodType(get, self)
            self.set = types.MethodType(set, self)
            self.clear = types.MethodType(clear, self) 
Example 16
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = _OrderedDict()

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.popitem(False)

                def clear(self):
                    cache.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self) 
Example 17
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 18
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = _OrderedDict()

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.popitem(False)

                def clear(self):
                    cache.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self) 
Example 19
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 20
Project: pcc   Author: jiamo   File: yacc.py    The Unlicense 6 votes vote down vote up
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map 
Example 21
Project: pcc   Author: jiamo   File: yacc.py    The Unlicense 6 votes vote down vote up
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_') or name == 'p_error':
                continue
            if isinstance(item, (types.FunctionType, types.MethodType)):
                line = item.__code__.co_firstlineno
                module = inspect.getmodule(item)
                p_functions.append((line, module, name, item.__doc__))

        # Sort all of the actions by line number; make sure to stringify
        # modules to make them sortable, since `line` may not uniquely sort all
        # p functions
        p_functions.sort(key=lambda p_function: (
            p_function[0],
            str(p_function[1]),
            p_function[2],
            p_function[3]))
        self.pfuncs = p_functions

    # Validate all of the p_functions 
Example 22
Project: loman   Author: janushendersonassetallocation   File: computeengine.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw(self, colors='state', cmap=None, graph_attr=None, node_attr=None, edge_attr=None, show_expansion=False):
        """
        Draw a computation's current state using the GraphViz utility

        :param graph_attr: Mapping of (attribute, value) pairs for the graph. For example ``graph_attr={'size': '"10,8"'}`` can control the size of the output graph
        :param node_attr: Mapping of (attribute, value) pairs set for all nodes.
        :param edge_attr: Mapping of (attribute, value) pairs set for all edges.
        :param show_expansion: Whether to show expansion nodes (i.e. named tuple expansion nodes) if they are not referenced by other nodes
        """
        d = self.to_pydot(colors=colors, cmap=cmap, graph_attr=graph_attr, node_attr=node_attr, edge_attr=edge_attr,
                          show_expansion=show_expansion)

        def repr_svg(self):
            return self.create_svg().decode('utf-8')

        d._repr_svg_ = types.MethodType(repr_svg, d)
        return d 
Example 23
Project: smartformat   Author: what-studio   File: smart.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, locale=None, extensions=(), register_default=True,
                 errors='strict'):
        super(SmartFormatter, self).__init__(locale)
        # Set error action.
        try:
            _format_error = self._error_formatters[errors]
        except KeyError:
            raise LookupError('unknown error action name %s' % errors)
        self.format_error = MethodType(_format_error, self)
        if errors == 'skip':
            self.parse = self._parse_for_skip_error_action
        self.errors = errors
        # Currently implemented only formatter extensions.
        self._extensions = {}
        if register_default:
            self.register(default_extensions)
        self.register(extensions) 
Example 24
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getmethparlist(ob):
    "Get strings describing the arguments for the given object"
    argText1 = argText2 = ""
    # bit of a hack for methods - turn it into a function
    # but we drop the "self" param.
    if type(ob)==types.MethodType:
        fob = ob.im_func
        argOffset = 1
    else:
        fob = ob
        argOffset = 0
    # Try and build one for Python defined functions
    if type(fob) in [types.FunctionType, types.LambdaType]:
        try:
            counter = fob.func_code.co_argcount
            items2 = list(fob.func_code.co_varnames[argOffset:counter])
            realArgs = fob.func_code.co_varnames[argOffset:counter]
            defaults = fob.func_defaults or []
            defaults = list(map(lambda name: "=%s" % repr(name), defaults))
            defaults = [""] * (len(realArgs)-len(defaults)) + defaults
            items1 = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
            if fob.func_code.co_flags & 0x4:
                items1.append("*"+fob.func_code.co_varnames[counter])
                items2.append("*"+fob.func_code.co_varnames[counter])
                counter += 1
            if fob.func_code.co_flags & 0x8:
                items1.append("**"+fob.func_code.co_varnames[counter])
                items2.append("**"+fob.func_code.co_varnames[counter])
            argText1 = ", ".join(items1)
            argText1 = "(%s)" % argText1
            argText2 = ", ".join(items2)
            argText2 = "(%s)" % argText2
        except:
            pass
    return argText1, argText2 
Example 25
Project: pyblish-win   Author: pyblish   File: random.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _randbelow(self, n, _log=_log, _int=int, _maxwidth=1L<<BPF,
                   _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType): 
Example 26
Project: pyblish-win   Author: pyblish   File: inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def ismethod(object):
    """Return true if the object is an instance method.

    Instance method objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this method was defined
        im_class        class object in which this method belongs
        im_func         function object containing implementation of method
        im_self         instance to which this method is bound, or None"""
    return isinstance(object, types.MethodType) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_descr.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_recursions_2(self):
        # Bug #1202533.
        class A(object):
            pass
        A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
        try:
            A()*2
        except RuntimeError:
            pass
        else:
            self.fail("expected a RuntimeError") 
Example 28
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sandbox.py    MIT License 5 votes vote down vote up
def inspect_format_method(callable):
    if not isinstance(callable, (types.MethodType,
                                 types.BuiltinMethodType)) or \
       callable.__name__ != 'format':
        return None
    obj = callable.__self__
    if isinstance(obj, string_types):
        return obj 
Example 29
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sandbox.py    MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 30
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 31
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example 32
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 5 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    while len(key_fifo) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                def cache_len(self):
                    return len(cache)

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)
                self.__len__ = types.MethodType(cache_len, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: six.py    MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: _azure.py    MIT License 5 votes vote down vote up
def _wrap(self, func, args, kwargs):
        if isinstance(func, MethodType):
            result = self._handle_temporary_redirects(lambda: func(*args, **kwargs))
        else:
            result = self._handle_temporary_redirects(lambda: func(self.other, *args, **kwargs))
        return result 
Example 38
Project: interact   Author: dongshengmu   File: interact.py    MIT License 5 votes vote down vote up
def register_method(self, method):
        """To register an add-on method for existing classs instance.

        - method: a funciton defined as foo(self, ...)
        - return: True if successfully regitered the add-on.
        """
        if method.__name__ in self.__dict__:
            self.print_error('Method %s is already exist in object %s.' % (method.__name__, self))
            return False
        self.__dict__[method.__name__] = types.MethodType(method, self)
        return True 
Example 39
Project: interact   Author: dongshengmu   File: interact.py    MIT License 5 votes vote down vote up
def register_method(self, method):
        """To register an add-on method for existing classs instance.

        - method: a funciton defined as foo(self, ...)
        - return: True if successfully regitered the add-on.
        """
        if method.__name__ in self.__dict__:
            self.print_error('Method %s is already exist in object %s.' % (method.__name__, self))
            return False
        self.__dict__[method.__name__] = types.MethodType(method, self)
        return True 
Example 40
Project: flasky   Author: RoseOu   File: registry.py    MIT License 5 votes vote down vote up
def __init__(self, target, identifier,
                 fn, dispatch_target, _fn_wrap=None):
        self.target = target
        self.identifier = identifier
        self.fn = fn
        if isinstance(fn, types.MethodType):
            self.fn_key = id(fn.__func__), id(fn.__self__)
        else:
            self.fn_key = id(fn)
        self.fn_wrap = _fn_wrap
        self.dispatch_target = dispatch_target 
Example 41
Project: flasky   Author: RoseOu   File: langhelpers.py    MIT License 5 votes vote down vote up
def unbound_method_to_callable(func_or_cls):
    """Adjust the incoming callable such that a 'self' argument is not
    required.

    """

    if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__:
        return func_or_cls.__func__
    else:
        return func_or_cls 
Example 42
Project: flasky   Author: RoseOu   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 43
Project: flasky   Author: RoseOu   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 44
Project: flasky   Author: RoseOu   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 45
Project: swaggerit   Author: dutradda   File: utils.py    MIT License 5 votes vote down vote up
def set_method(obj, method, method_name=None):
    if method_name is None:
        method_name = method.__name__

    if not hasattr(obj, method_name):
        setattr(obj, method_name, MethodType(method, obj)) 
Example 46
Project: swaggerit   Author: dutradda   File: _base.py    MIT License 5 votes vote down vote up
def _init(obj, name):
    if hasattr(obj, '__model_base__'):
        name = name.replace('Model', '')
        key = obj.__key__ = getattr(obj, '__key__', _camel_case_convert(name))

        if key in _all_models:
            raise SwaggerItModelError("The model '{}' was already registered with name '{}'."
                .format(_all_models[key].__name__, key))

        _all_models[key] = obj

    set_logger(obj)
    obj.get_model = MethodType(_get_model, obj)
    obj._unpack_obj = MethodType(_unpack_obj, obj)
    obj._pack_obj = MethodType(_pack_obj, obj) 
Example 47
Project: Splunk_CBER_App   Author: MHaggis   File: six.py    MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example 48
Project: Splunk_CBER_App   Author: MHaggis   File: six.py    MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example 49
Project: smach_based_introspection_framework   Author: birlrobotics   File: modify_user_sm.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(sm):
    import smach
    with sm:
        raw_user_states = copy.deepcopy(sm._states)

        # redirect all NeedRecovery to their respective anomay diagnosis
        for user_state in raw_user_states:
            obj = sm._states[user_state]
            obj.execute = types.MethodType(introspection_execute.execute, obj)
            obj._outcomes.add("Revert") 

            state_name = user_state 
            state_transitions = sm._transitions[state_name]
            state_transitions["Revert"] = RollBackRecovery.__name__ 

        # build Recovery states automatically
        recovery_outcomes = ['RecoveryFailed']
        recovery_state_transitions = {
            'RecoveryFailed': 'TaskFailed'
        }
        for user_state in raw_user_states:
            state_name = user_state 
            recovery_outcomes.append('Reenter_'+state_name)
            recovery_state_transitions['Reenter_'+state_name] = state_name

        smach.StateMachine.add(
			RollBackRecovery.__name__,
			RollBackRecovery(outcomes=recovery_outcomes),
            transitions=recovery_state_transitions
        )

    return sm 
Example 50
Project: zippy   Author: Illumina   File: zippy.py    Apache License 2.0 5 votes vote down vote up
def addWorkflowTask(self, label, workflowRunnerInstance, dependencies=None):
        '''
        We inject a docker-aware addTask function into subworkflows.
        '''
        workflowRunnerInstance.addTask = types.MethodType(partial(subworkflow_addTask, self.current_stage_setup, self.params), workflowRunnerInstance)
        return WorkflowRunner.addWorkflowTask(self, label, workflowRunnerInstance, dependencies=dependencies)