Python types.MethodType() Examples

The following are 30 code examples of types.MethodType(). 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 types , or try the search function .
Example #1
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 #2
Source File: runtime.py    From misp42splunk with GNU Lesser General Public License v3.0 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 #3
Source File: log_api.py    From mlimages with 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
Source File: csv.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
def forEachLine(filePath, parser):
    """
        For each line of the file call the parser, at the end call the finalize method of the parser if it`s defined.
    """
    try:
        f = open(os.path.normpath(filePath), 'r')
    except Exception:
        sys.stderr.write('Cannot open a file for reading: ' + filePath)
        raise
    else:
        try:
            for line in f:
                parser.parse(noNewLine(line))
        except Exception:
            sys.stderr.write('Cannot read from file: ' + filePath)
            raise
        finally:
            f.close()
    try:
        if isinstance(parser.finalize, types.MethodType):
            parser.finalize()
    except Exception:
        pass

    return parser 
Example #5
Source File: yacc.py    From misp42splunk with GNU Lesser General Public License v3.0 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 #6
Source File: yacc.py    From SublimeKSP with GNU General Public License v3.0 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 = 1
                return

            eline = func_code(self.error_func).co_firstlineno
            efile = func_code(self.error_func).co_filename
            module = inspect.getmodule(self.error_func)
            self.modules[module] = 1

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

    # Get the tokens map 
Example #7
Source File: yacc.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_'): continue
            if name == 'p_error': continue
            if isinstance(item,(types.FunctionType,types.MethodType)):
                line = func_code(item).co_firstlineno
                module = inspect.getmodule(item)
                p_functions.append((line,module,name,item.__doc__))

        # Sort all of the actions by line number
        p_functions.sort()
        self.pfuncs = p_functions


    # Validate all of the p_functions 
Example #8
Source File: yacc.py    From misp42splunk with GNU Lesser General Public License v3.0 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 #9
Source File: __init__.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def bind_method(cls, name, func):
    """Bind a method to class, python 2 and python 3 compatible.

    Parameters
    ----------

    cls : type
        class to receive bound method
    name : basestring
        name of method on class instance
    func : function
        function to be bound as method

    Returns
    -------
    None
    """
    # only python 2 has an issue with bound/unbound methods
    if not PY3:
        setattr(cls, name, types.MethodType(func, None, cls))
    else:
        setattr(cls, name, func) 
Example #10
Source File: decorators.py    From django-rest-registration with MIT License 6 votes vote down vote up
def api_view_serializer_class_getter(serializer_class_getter):

    def _get_serializer_class(self):
        return serializer_class_getter()

    def _get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        return serializer_class(*args, **kwargs)

    def decorator(func):
        if not hasattr(func, 'cls'):
            raise Exception(
                '@api_view_serializer_class_getter can only decorate'
                ' @api_view decorated functions')
        apiview_cls = func.cls
        apiview_cls.get_serializer_class = types.MethodType(
            _get_serializer_class,
            apiview_cls)
        if not hasattr(apiview_cls, 'get_serializer'):
            # In case get_serializer() method is missing.
            apiview_cls.get_serializer = types.MethodType(
                _get_serializer,
                apiview_cls)
        return func
    return decorator 
Example #11
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def bind_method(cls, name, func):
    """Bind a method to class, python 2 and python 3 compatible.

    Parameters
    ----------

    cls : type
        class to receive bound method
    name : basestring
        name of method on class instance
    func : function
        function to be bound as method

    Returns
    -------
    None
    """
    # only python 2 has an issue with bound/unbound methods
    if not PY3:
        setattr(cls, name, types.MethodType(func, None, cls))
    else:
        setattr(cls, name, func) 
Example #12
Source File: yacc.py    From misp42splunk with GNU Lesser General Public License v3.0 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 = getattr(item, 'co_firstlineno', 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 #13
Source File: six.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example #14
Source File: lex.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _form_master_re(relist, reflags, ldict, toknames):
    if not relist:
        return []
    regex = '|'.join(relist)
    try:
        lexre = re.compile(regex, reflags)

        # Build the index to function map for the matching engine
        lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1)
        lexindexnames = lexindexfunc[:]

        for f, i in lexre.groupindex.items():
            handle = ldict.get(f, None)
            if type(handle) in (types.FunctionType, types.MethodType):
                lexindexfunc[i] = (handle, toknames[f])
                lexindexnames[i] = f
            elif handle is not None:
                lexindexnames[i] = f
                if f.find('ignore_') > 0:
                    lexindexfunc[i] = (None, None)
                else:
                    lexindexfunc[i] = (None, toknames[f])

        return [(lexre, lexindexfunc)], [regex], [lexindexnames]
    except Exception:
        m = int(len(relist)/2)
        if m == 0:
            m = 1
        llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames)
        rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames)
        return (llist+rlist), (lre+rre), (lnames+rnames)

# -----------------------------------------------------------------------------
# def _statetoken(s,names)
#
# Given a declaration name s of the form "t_" and a dictionary whose keys are
# state names, this function returns a tuple (states,tokenname) where states
# is a tuple of state names and tokenname is the name of the token.  For example,
# calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
# ----------------------------------------------------------------------------- 
Example #15
Source File: base.py    From tomodachi with MIT License 5 votes vote down vote up
def decorator(cls, cls_func: Callable) -> Callable:
        def _wrapper(*args: Any, **kwargs: Any) -> Callable:
            def wrapper(func: Callable) -> Callable:
                @functools.wraps(func)
                async def _decorator(obj: Any, *a: Any, **kw: Any) -> Any:
                    if not getattr(_decorator, START_ATTRIBUTE, None):
                        return await func(obj, *a, **kw)

                    setattr(_decorator, START_ATTRIBUTE, False)
                    if not cls.context.get(obj, None):
                        if getattr(obj, "context", None):
                            cls.context[obj] = obj.context
                        else:
                            cls.context[obj] = {}
                        cls.context[obj].update({i: getattr(obj, i) for i in dir(obj) if not callable(i) and not i.startswith("__") and not isinstance(getattr(obj, i), types.MethodType)})
                    context = cls.context[obj]
                    obj.context = context
                    start_func = await cls_func(cls, obj, context, func, *args, **kwargs)
                    return start_func

                setattr(_decorator, FUNCTION_ATTRIBUTE, True)
                return _decorator

            if not kwargs and len(args) == 1 and callable(args[0]):
                func = args[0]
                args = ()
                return wrapper(func)
            else:
                return wrapper
        return _wrapper 
Example #16
Source File: six.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #17
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #18
Source File: six.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example #19
Source File: six.py    From core with MIT License 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #20
Source File: sandbox.py    From misp42splunk with GNU Lesser General Public License v3.0 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 #21
Source File: sandbox.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def inspect_format_method(callable):
    if not isinstance(callable, (types.MethodType,
                                 types.BuiltinMethodType)) or \
       callable.__name__ not in ('format', 'format_map'):
        return None
    obj = callable.__self__
    if isinstance(obj, string_types):
        return obj 
Example #22
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #23
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example #24
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #25
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #26
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example #27
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_unbound_method(func, cls):
        return types.MethodType(func, None, cls) 
Example #28
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__) 
Example #29
Source File: lex.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _form_master_re(relist, reflags, ldict, toknames):
    if not relist:
        return []
    regex = '|'.join(relist)
    try:
        lexre = re.compile(regex, reflags)

        # Build the index to function map for the matching engine
        lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1)
        lexindexnames = lexindexfunc[:]

        for f, i in lexre.groupindex.items():
            handle = ldict.get(f, None)
            if type(handle) in (types.FunctionType, types.MethodType):
                lexindexfunc[i] = (handle, toknames[f])
                lexindexnames[i] = f
            elif handle is not None:
                lexindexnames[i] = f
                if f.find('ignore_') > 0:
                    lexindexfunc[i] = (None, None)
                else:
                    lexindexfunc[i] = (None, toknames[f])

        return [(lexre, lexindexfunc)], [regex], [lexindexnames]
    except Exception:
        m = int(len(relist)/2)
        if m == 0:
            m = 1
        llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames)
        rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames)
        return (llist+rlist), (lre+rre), (lnames+rnames)

# -----------------------------------------------------------------------------
# def _statetoken(s,names)
#
# Given a declaration name s of the form "t_" and a dictionary whose keys are
# state names, this function returns a tuple (states,tokenname) where states
# is a tuple of state names and tokenname is the name of the token.  For example,
# calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
# ----------------------------------------------------------------------------- 
Example #30
Source File: sandbox.py    From misp42splunk with GNU Lesser General Public License v3.0 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('__')