• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python types.FunctionType类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中types.FunctionType的典型用法代码示例。如果您正苦于以下问题:Python FunctionType类的具体用法?Python FunctionType怎么用?Python FunctionType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FunctionType类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: chained_function

 def chained_function(meta, func, mod):
     d = ModuleChainedDict(mod.__dict__, func.__globals__)
     newfunc = FunctionType(func.__code, d)
     newfunc.__doc__ = func.__doc__
     newfunc.__defaults__ = newfunc.__defaults__
     newfunc.__kwdefaults__ = func.__kwdefaults__
     return newfunc
开发者ID:felipecruz,项目名称:pyjulia,代码行数:7,代码来源:core.py


示例2: _deserialize_func

def _deserialize_func(funcs, globalDict):
    items = pickle.loads(funcs)
    res = None
    for objType, name, data in items:
        if objType == 'func':
            codeArgs, funcArgs, updatedGlobals = pickle.loads(data)
            code = CodeType(*codeArgs)    
    
            globalDict.update(**updatedGlobals)

            value = FunctionType(code, globalDict, *funcArgs)
        elif objType == 'mod':
            value = __import__(data)
        elif objType == 'oldclass':
            class_name, module, bases, class_dict = data
            value = typesmod.ClassType(class_name, bases, {k:_deserialize_func(v, globalDict) for k, v in class_dict.items()})
            value.__module__ = module
        elif objType == 'type':
            raise Exception('deserialize type')
        else:
            raise Exception('Unknown serialization type')
        globalDict[name] = value

        if res is None:
            res = value

    return res
开发者ID:amykatenicho,项目名称:Azure-MachineLearning-ClientLibrary-Python,代码行数:27,代码来源:services.py


示例3: newObjCpt

    def newObjCpt(self, elt):

        argNames = self.__code__.co_varnames[:self.__code__.co_argcount]
        argValues = [elt]

        wfunc = FunctionType(self.__code__, self.__globals__)

        class Process(object):
            __call__ = staticmethod(wfunc)

            def __setattr__(s, name, value):
                argValues[argNames.index(name)] = value
                wfunc.__defaults__ = tuple(argValues)

            def __getattr__(s, name):
                return argValues[argNames.index(name)]

            @classmethod
            def __cptDefs__(cls):
                cpts= {name : cpt for (name, cpt) in zip( argNames, self.__defaults__) if isinstance(cpt, _cptDef)}
                return  sorted(cpts.items(),key =lambda item:item[1].id)

        process = Process()

        argValues += [p.newObjCpt(process) for p in   self.__defaults__[1:]]

        wfunc.__defaults__ = tuple(argValues)
        return process
开发者ID:abosc,项目名称:goplus-model,代码行数:28,代码来源:goELT.py


示例4: build_get_single_ctrl

def build_get_single_ctrl(query, args_names, field_names):
    """
    Create optimized controller.
    """

    codes = [
        opcode.opmap['LOAD_GLOBAL'], 0, 0,
        opcode.opmap['LOAD_CONST'], 1, 0
    ]

    for i in range(len(args_names)):
        codes.extend((opcode.opmap['LOAD_FAST'], i, 0))

    codes.extend((
        opcode.opmap['BUILD_TUPLE'], len(args_names), 0,
        opcode.opmap['CALL_FUNCTION'], 2, 0,
        opcode.opmap['LOAD_ATTR'], 1, 0,
        opcode.opmap['CALL_FUNCTION'], 0, 0,
        opcode.opmap['STORE_FAST'], len(args_names), 0,  # store to 'values'

        opcode.opmap['LOAD_FAST'], len(args_names), 0,  # load from 'values'
        opcode.opmap['LOAD_CONST'], 0, 0,
        opcode.opmap['COMPARE_OP'], 8, 0,
        opcode.opmap['POP_JUMP_IF_FALSE'], len(args_names) * 3 + 37, 0,

        opcode.opmap['LOAD_FAST'], len(args_names), 0,
        opcode.opmap['RETURN_VALUE'],

        opcode.opmap['LOAD_GLOBAL'], 2, 0, # (dict)
        opcode.opmap['LOAD_GLOBAL'], 3, 0, # (zip)
        opcode.opmap['LOAD_CONST'], 2, 0,
        opcode.opmap['LOAD_FAST'], len(args_names), 0, # load from 'values'
        opcode.opmap['CALL_FUNCTION'], 2, 0,
        opcode.opmap['CALL_FUNCTION'], 1, 0,
        opcode.opmap['RETURN_VALUE'],
    ))

    ctrl = FunctionType(
        CodeType(
            len(args_names),  #  argcount
            0,  #  kwonlyargcount
            len(args_names) + 1,  # + nb var used
            7,  # stacksize
            67,  # flags
            bytes(codes),  # codestring
            (None, query, field_names),  # constants
            ('sql_execute', 'fetchone', 'dict', 'zip'),  # names
            tuple(args_names) + ('values',),  # varnames + var used
            __file__,  # filename
            'ctrl',  # name
            0,  # firstlineno
            b'\x00\x01\x1b\x01\x0c\x01\x04\x01'  # lnotab
        ), {'dict': dict, 'zip': zip, 'sql_execute': MetaResource.db.execute}
    )
    ctrl.single = True
    ctrl.optimizable = True
    return ctrl
开发者ID:Maillol,项目名称:woof,代码行数:57,代码来源:optimizer.py


示例5: _create_function

def _create_function(fcode, fglobals, fname=None, fdefaults=None, fclosure=None, fdict=None, mod_name=None):
    # same as FunctionType, but enable passing __dict__ to new function,
    # __dict__ is the storehouse for attributes added after function creation
    log.info('loading function: ' + fname)
    fdict = fdict or dict()
    fglobals = fglobals or {}
    func = FunctionType(fcode, fglobals, fname, fdefaults, fclosure)
    func.__dict__.update(fdict)
    func.__module__ = mod_name
    return func
开发者ID:wxiang7,项目名称:dill,代码行数:10,代码来源:dill.py


示例6: handle_deffun

 def handle_deffun(self, func, fdict, fdoc, remote_globals):
   func = self.unpack(func)
   g = globals()
   glbls = {k:g[k] for k in remote_globals if k in g} if remote_globals is not None else g.copy()
   glbls.update(func[1])
   func[1].update(glbls)
   f = FunctionType(*func)
   f.__dict__ = self.unpack(fdict)
   f.__doc__ = self.unpack(fdoc)
   return self.pack(f)
开发者ID:heartbleeded,项目名称:qira,代码行数:10,代码来源:remoteobj.py


示例7: __new__

    def __new__(cls, mplayer=MPLAYER_PATH, pipe=PIPE_PATH, 
                     stdout=STDOUT_PATH, pid=PID_PATH, debug=False):

        def _doc_creator(item):
            ## Doc creator for the command
            doc_info  = item['comment']
            py_command = item['pycommand']
            doc = '%s\n%s' % (py_command, doc_info)
            return doc

        ## Creating new class methods from mplayer cmdlist_dict
        cmdlist_dict = CmdDictGenerator(mplayer).get_cmdlist()
        for item in cmdlist_dict.keys():
            if item == 'get_property': continue
            if item == 'set_property': continue
            #if item == 'set_property_osd': continue
            doc = _doc_creator(cmdlist_dict[item])
            # Creating a dictionary that would include variables from 
            # item and globals() (excluding locals()).
            # This is necessary for passing it to a new method.
            method_dict = {'item': cmdlist_dict[item]}
            for i in globals().keys():
                if i in locals().keys(): continue
                method_dict[i] = globals()[i]
            # Creating a function
            if 'get' not in item:
                if len(cmdlist_dict[item]['types']) != 0:
                    # If list of types contains some types
                    new_method = FunctionType(cls._new_args_method.func_code,
                                              method_dict,
                                              item)
                else:
                    # If list of types is empty
                    new_method = FunctionType(cls._new_simple_method.func_code,
                                              method_dict,
                                              item)
            else:
                new_method = FunctionType(cls._new_get_method.func_code,
                                          method_dict,
                                          item)
            # Adding doc, editing name
            new_method.__doc__ = doc
            new_method.__name__ = item
            # Adding function to this class as a method
            setattr(cls, item, new_method)
        # Create 'properties' property and 
        # making it use the doc from Properties class
        properties_class = Properties()
        def get_properties(self):
            return properties_class
        properties = property(fget=get_properties, 
                              doc=Properties.__doc__)
        setattr(cls, 'properties', properties)
        return super(Player, cls).__new__(cls)
开发者ID:Seg-mel,项目名称:mplayer_control,代码行数:54,代码来源:player.py


示例8: interpolate

    def interpolate(self, obj, name):
        """Inject the formatted listing in the second blank line of `name`."""
        f = getattr(obj, name)
        f2 = FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)

        # Conveniently the original docstring is on f2, not the new ones if
        # inheritence is happening. I have no idea why.
        t = f2.__doc__.split("\n\n")
        t.insert(2, self.formatted_listing())
        f2.__doc__ = "\n\n".join(t)

        setattr(obj, name, f2)
开发者ID:RNAer,项目名称:scikit-bio,代码行数:12,代码来源:_misc.py


示例9: interactive

def interactive(f):
    """decorator for making functions appear as interactively defined.
    This results in the function being linked to the user_ns as globals()
    instead of the module globals().
    """

    # build new FunctionType, so it can have the right globals
    # interactive functions never have closures, that's kind of the point
    if isinstance(f, FunctionType):
        mainmod = __import__("__main__")
        f = FunctionType(f.__code__, mainmod.__dict__, f.__name__, f.__defaults__)
    # associate with __main__ for uncanning
    f.__module__ = "__main__"
    return f
开发者ID:JuDa-hku,项目名称:ipython,代码行数:14,代码来源:util.py


示例10: buildFunction

def buildFunction(baseFunc, code=None, glbls=None,
                  name=None, defaults=None,
                  kwdefaults=None, closure=None,
                  annotations=None, doc=None, dct=None):

    resf = None

    def _f():
        pass

    if hasattr(_f, 'func_code'):
        # Python 2.x
        resf = FunctionType(code or baseFunc.func_code,
                            glbls or baseFunc.func_globals,
                            name or baseFunc.func_name,
                            defaults or baseFunc.func_defaults,
                            closure or baseFunc.func_closure)
        resf.func_dict = dct or baseFunc.func_dict
        resf.func_doc = doc or baseFunc.func_doc

    else:
        # Python 3.x
        resf = FunctionType(code or baseFunc.__code__,
                            glbls or baseFunc.__globals__,
                            name or baseFunc.__name__,
                            defaults or baseFunc.__defaults__,
                            closure or baseFunc.__closure__)
        resf.__kwdefaults__ = kwdefaults or baseFunc.__kwdefaults__
        resf.__annotations__ = annotations or baseFunc.__annotations__
        resf.__dict__ = dct or baseFunc.__dict__
        resf.__doc__ = doc or baseFunc.__doc__

    return resf
开发者ID:DirectXMan12,项目名称:should_be,代码行数:33,代码来源:core.py


示例11: loads_function

def loads_function(s):
    '''Restores a function serialized with :func:`dumps_function`.'''
    name, code, globals_, defaults, closure, func_dict = loads(s)
    code = marshal.loads(code)
    for k, v in globals_.iteritems():
        if isinstance(v, Module):
            globals_[k] = v.mod
    if closure is not None:
        import ctypes
        ctypes.pythonapi.PyCell_New.restype = ctypes.py_object
        ctypes.pythonapi.PyCell_New.argtypes = [ctypes.py_object]
        closure = tuple(ctypes.pythonapi.PyCell_New(c) for c in closure)
    r = FunctionType(code, globals_, name, defaults, closure)
    r.func_dict = func_dict
    return r
开发者ID:andreasbuhr,项目名称:pymor,代码行数:15,代码来源:pickle.py


示例12: rust_bind

def rust_bind(fn: FunctionType) -> FunctionType:
    if hasattr(fn, '_bind_to_rust'):
        raise AttributeError(
            "the attribute name `_bind_to_rust` is reserved for binding "
            "functions of RustyPy")
    fn._bind_to_rust = True
    return fn
开发者ID:iduartgomez,项目名称:rustypy,代码行数:7,代码来源:pywrapper.py


示例13: reader

def reader(name=None, doc=None):
    """Construct a new unified input/output reader.

    This method is required to create a new copy of the
    :func:`astropy.io.registry.read` with a dynamic docstring.

    Returns
    -------
    read : `function`
        A copy of the :func:`astropy.io.registry.read` function
    """
    func = FunctionType(read.func_code, read.func_globals,
                        name or read.func_name, read.func_defaults,
                        read.func_closure)
    if doc is not None:
        func.__doc__ = doc.strip('\n ')
    return func
开发者ID:JackieXie168,项目名称:gwpy,代码行数:17,代码来源:__init__.py


示例14: writer

def writer(doc=None):
    """Construct a new unified input/output writeer.

    This method is required to create a new copy of the
    :func:`astropy.io.registry.write` with a dynamic docstring.

    Returns
    -------
    write : `function`
        A copy of the :func:`astropy.io.registry.write` function
    """
    func = FunctionType(write.func_code, write.func_globals,
                        write.func_name, write.func_defaults,
                        write.func_closure)
    if doc is not None:
        func.__doc__ = doc.strip('\n ')
    return func
开发者ID:bfarr,项目名称:gwpy,代码行数:17,代码来源:__init__.py


示例15: interpolate

    def interpolate(self, obj, name):
        """Inject the formatted listing in the second blank line of `name`."""
        # Py2/3 compatible way of calling getattr(obj, name).__func__
        f = getattr(obj, name).__get__(None, type(None))

        if hasattr(f, 'func_code'):
            f2 = FunctionType(f.func_code, f.func_globals, name=f.func_name,
                              argdefs=f.func_defaults, closure=f.func_closure)
        else:
            f2 = FunctionType(f.__code__, f.__globals__, name=f.__name__,
                              argdefs=f.__defaults__, closure=f.__closure__)
        # Conveniently the original docstring is on f2, not the new ones if
        # inheritence is happening. I have no idea why.
        t = f2.__doc__.split("\n\n")
        t.insert(2, self.formatted_listing())
        f2.__doc__ = "\n\n".join(t)

        setattr(obj, name, f2)
开发者ID:bctaylor,项目名称:scikit-bio,代码行数:18,代码来源:_misc.py


示例16: setup_bindings

def setup_bindings(instance, bindings, identifiers, f_globals):
    """ Setup the expression bindings for a declarative instance.

    Parameters
    ----------
    instance : Declarative
        The declarative instance which owns the bindings.

    bindings : list
        A list of binding dicts created by the enaml compiler.

    identifiers : dict
        The identifiers scope to associate with the bindings.

    f_globals : dict
        The globals dict to associate with the bindings.

    """
    operators = instance.operators
    for binding in bindings:
        opname = binding['operator']
        try:
            operator = operators[opname]
        except KeyError:
            filename = binding['filename']
            lineno = binding['lineno']
            block = binding['block']
            raise OperatorLookupError(opname, filename, lineno, block)
        code = binding['code']
        # If the code is a tuple, it represents a delegation
        # expression which is a combination of subscription
        # and update functions.
        if isinstance(code, tuple):
            sub_code, upd_code = code
            func = FunctionType(sub_code, f_globals)
            func._update = FunctionType(upd_code, f_globals)
        else:
            func = FunctionType(code, f_globals)
        operator(instance, binding['name'], func, identifiers)
开发者ID:5n1p,项目名称:enaml,代码行数:39,代码来源:declarative.py


示例17: __init__

 def __init__(self,func):
     for n in list(n for n in set(dir(func)) - set(dir(self)) if n != '__class__'):
         setattr(self, n, getattr(func, n))
     self._m=Manager()
     self._e= self._m.Event()
     self._d=self._m.dict()
     self._f=dumps(func.__code__)
     self._n=func.__name__
     self._q=Queue()
     self.func=FunctionType(loads(self._f),globals(),"a_func")
     globals()[self._n]=partial(_getValue,self._d,self._q,self._e,True,self.func)
     globals()[self._n].apply_async=partial(_getValue,self._d,self._q,self._e,False,self.func)
     self._t=Process(target=_taskManager,args=(self._q,self._d,self._f,self._n, self._e))
     self._t.start()
开发者ID:cdusold,项目名称:PySpeedup,代码行数:14,代码来源:_primer.py


示例18: _clone

def _clone(origin_fun, new_fun_name, name, extra=None):
    # update the checkers/accessors dico
    original_checkers = origin_fun.checker.arg_type_list
    new_dict = dict(original_checkers)

    if extra is not None:
        new_dict.update(extra)

    # clone the function
    new_fun = FunctionType(code=origin_fun.__code__,
                           globals=origin_fun.__globals__,
                           name=new_fun_name,
                           argdefs=origin_fun.__defaults__,
                           closure=origin_fun.__closure__)

    # apply decorator
    fun_decorator = shellMethod(**new_dict)
    fun_decorator(new_fun)

    # updat the docstring
    new_fun.__doc__ = new_fun.__doc__.replace("environment", name)

    return new_fun
开发者ID:djoproject,项目名称:pyshell,代码行数:23,代码来源:parameter.py


示例19: __init__

 def __init__(self,func):
     for n in list(n for n in set(dir(func)) - set(dir(self)) if n != '__class__'):
         setattr(self, n, getattr(func, n))
     setattr(self, "__doc__", getattr(func, "__doc__"))
     self._m=Manager()
     self._e= self._m.Event()
     self._d=self._m.dict()
     self._f=dumps(func.__code__)
     self._n=func.__name__
     self._q=Queue()
     self.func=FunctionType(loads(self._f),globals(),"a_func")
     globals()[self._n]=partial(_getValue,self._d,self._q,self._e,True,self.func)
     globals()[self._n].apply_async=partial(_getValue,self._d,self._q,self._e,False,self.func)
     globals()[self._n].batch_async=partial(_batchAsync,self._d,self._q,self.func)
     #setattr(globals()[self._n],"__contains__",self.__contains__)
     self._t=Process(target=_taskManager,args=(self._q,self._d,self._f,self._n, self._e))
     self._t.start()
     atexit.register(_closeProcessGracefully, self) #TODO: Make this line not necessary.
开发者ID:cdusold,项目名称:PySpeedup,代码行数:18,代码来源:_cache.py


示例20: Primer

class Primer():
    '''An asynchronous cache implementation. Maintains multiple recursive calls stably.'''
    def __init__(self,func):
        for n in list(n for n in set(dir(func)) - set(dir(self)) if n != '__class__'):
            setattr(self, n, getattr(func, n))
        self._m=Manager()
        self._e= self._m.Event()
        self._d=self._m.dict()
        self._f=dumps(func.__code__)
        self._n=func.__name__
        self._q=Queue()
        self.func=FunctionType(loads(self._f),globals(),"a_func")
        globals()[self._n]=partial(_getValue,self._d,self._q,self._e,True,self.func)
        globals()[self._n].apply_async=partial(_getValue,self._d,self._q,self._e,False,self.func)
        self._t=Process(target=_taskManager,args=(self._q,self._d,self._f,self._n, self._e))
        self._t.start()
    def apply_async(self,*item):
        return _getValue(self._d,self._q,self._e,False,self.func,*item)
    def __call__(self,*item):
        return _getValue(self._d,self._q,self._e,True,self.func,*item)
    def __del__(self):
        self._t.terminate()
    def __repr__(self):
        return 'concurrent.Cache('+self.func.__repr__()+')'
开发者ID:cdusold,项目名称:PySpeedup,代码行数:24,代码来源:_primer.py



注:本文中的types.FunctionType类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python types.MappingProxyType类代码示例发布时间:2022-05-27
下一篇:
Python types.new_class函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap