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

Python new.function函数代码示例

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

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



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

示例1: _exec

    def _exec(self, bound_names, args, kw):
        """Call a Python Script

        Calling a Python Script is an actual function invocation.
        """
        # do caching
        keyset = None
        if self.ZCacheable_isCachingEnabled():
            # Prepare a cache key.
            keyset = kw.copy()
            asgns = self.getBindingAssignments()
            name_context = asgns.getAssignedName('name_context', None)
            if name_context:
                keyset[name_context] = self.aq_parent.getPhysicalPath()
            name_subpath = asgns.getAssignedName('name_subpath', None)
            if name_subpath:
                keyset[name_subpath] = self._getTraverseSubpath()
            # Note: perhaps we should cache based on name_ns also.
            keyset['*'] = args
            result = self.ZCacheable_get(keywords=keyset, default=_marker)
            if result is not _marker:
                # Got a cached value.
                return result

        # Prepare the function.
        f = self._v_f
        if f is None:
            # The script has errors.
            __traceback_supplement__ = (
                FSPythonScriptTracebackSupplement, self, 0)
            raise RuntimeError, '%s has errors.' % self._filepath

        # Updating func_globals directly is not thread safe here.
        # In normal PythonScripts, every thread has its own
        # copy of the function.  But in FSPythonScripts
        # there is only one copy.  So here's another way.
        new_globals = f.func_globals.copy()
        new_globals['__traceback_supplement__'] = (
            FSPythonScriptTracebackSupplement, self)
        new_globals['__file__'] = self._filepath
        new_globals['__name__'] = self.id
        if bound_names:
            new_globals.update(bound_names)
        if f.func_defaults:
            f = new.function(f.func_code, new_globals, f.func_name,
                             f.func_defaults)
        else:
            f = new.function(f.func_code, new_globals, f.func_name)

        # Execute the function in a new security context.
        security=getSecurityManager()
        security.addContext(self)
        try:
            result = f(*args, **kw)
            if keyset is not None:
                # Store the result in the cache.
                self.ZCacheable_set(result, keywords=keyset)
            return result
        finally:
            security.removeContext(self)
开发者ID:goschtl,项目名称:zope,代码行数:60,代码来源:FSPythonScript.py


示例2: test_closure

def test_closure(func, closure, exc):
    try:
        new.function(func.func_code, {}, "", None, closure)
    except exc:
        pass
    else:
        print "corrupt closure accepted"
开发者ID:BackupTheBerlios,项目名称:pyasynchio-svn,代码行数:7,代码来源:test_new.py


示例3: _exec

    def _exec(self, bound_names, args, kw):
        """Call a Python Script

        Calling a Python Script is an actual function invocation.
        """
        self._updateFromFS()
        # Prepare the function.
        f = self._v_f

        __traceback_info__ = bound_names, args, kw, self.func_defaults

        if bound_names:
            # Updating func_globals directly is not thread safe here.
            # In normal PythonScripts, every thread has its own
            # copy of the function.  But in FSPythonScripts
            # there is only one copy.  So here's another way.
            new_globals = f.func_globals.copy()
            new_globals.update(bound_names)
            if f.func_defaults:
                f = new.function(f.func_code, new_globals, f.func_name,
                                 f.func_defaults)
            else:
                f = new.function(f.func_code, new_globals, f.func_name)

        # Execute the function in a new security context.
        security=getSecurityManager()
        security.addContext(self)
        try:
            result = apply(f, args, kw)
            return result
        finally:
            security.removeContext(self)
开发者ID:goschtl,项目名称:zope,代码行数:32,代码来源:FSPythonScript.py


示例4: uncover

def uncover(function):
    name = function.func_name
    code = function.func_code

    name = name[1:] if name[0] == "_" else name
    arguments = tuple((name[1:] if name[0] == "_" else name)
        for name in code.co_varnames[:code.co_argcount])

    new_code = new.code(
        code.co_argcount,
        code.co_nlocals,
        code.co_stacksize,
        code.co_flags,
        code.co_code,
        code.co_consts,
        code.co_names,
        arguments + code.co_names,
        code.co_filename,
        code.co_name,
        code.co_firstlineno,
        code.co_lnotab)

    print function.func_closure

    new_function = new.function(
        new_code,
        function.func_globals,
        name,
        function.func_defaults,
        function.func_closure)

    return new_function
开发者ID:VDOMBoxGroup,项目名称:runtime2.0,代码行数:32,代码来源:decorators.py


示例5: __makeTest

def __makeTest(testName, html, text):
    testName = "test%s" % (testName,)
    testLambda = lambda self: self._testHTML2Markdown(html, text)
    testFunction = new.function(testLambda.func_code, {}, testName,
                                closure=testLambda.func_closure)
    setattr(HTML2MarkdownTests, testName,
            new.instancemethod(testFunction, None, HTML2MarkdownTests))
开发者ID:davelab6,项目名称:html2markdown,代码行数:7,代码来源:tests.py


示例6: __exit__

 def __exit__(self,*args):
     frame = self._get_context_frame()
     retcode = super(namespace,self).__exit__(*args)
     funcode = copy.deepcopy(self.bytecode)
     #  Ensure it's a properly formed func by always returning something
     funcode.code.append((LOAD_CONST,None))
     funcode.code.append((RETURN_VALUE,None))
     #  Switch LOAD/STORE/DELETE_FAST/NAME to LOAD/STORE/DELETE_ATTR
     to_replace = []
     for (i,(op,arg)) in enumerate(funcode.code):
         repl = self._replace_opcode((op,arg),frame)
         if repl:
             to_replace.append((i,repl))
     offset = 0
     for (i,repl) in to_replace:
         funcode.code[i+offset:i+offset+1] = repl
         offset += len(repl) - 1
     #  Create function object to do the manipulation
     funcode.args = ("_[namespace]",)
     funcode.varargs = False
     funcode.varkwargs = False
     funcode.name = "<withhack>"
     gs = self._get_context_frame().f_globals
     func = new.function(funcode.to_code(),gs)
     #  Execute bytecode in context of namespace
     retval = func(self.namespace)
     if self.as_name is not None:
         self._set_context_locals({self.as_name:self.namespace})
     return retcode
开发者ID:pombredanne,项目名称:withhacks,代码行数:29,代码来源:__init__.py


示例7: compileMultiFn

def compileMultiFn(comp, name, form):
    s = form
    argdefs = []
    while s is not None:
        argdefs.append(MultiFn(comp, s.first()))
        s = s.next()
    argdefs = sorted(argdefs, lambda x, y: len(x.args) < len(y.args))
    if len(filter(lambda x: x.lastisargs, argdefs)) > 1:
        raise CompilerException("Only one function overload may have variable number of arguments", form)


    code = []
    args = []
    for x in argdefs:
        code.extend(x.code)
        for x in x.args:
            if x not in args:
                args.append(x)

    code.append((LOAD_CONST, Exception))
    code.append((CALL_FUNCTION, 0))
    code.append((RAISE_VARARGS, 1))

    c = Code(code, comp.closureList(), ["__argsv__"], True, False, True, str(Symbol.intern(comp.getNS().__name__, name.name)), "./clj/clojure/core.clj", 0, None)

    fn = new.function(c.to_code(), comp.ns.__dict__, name.name)

    return [(LOAD_CONST, fn)]
开发者ID:AlexBaranosky,项目名称:clojure-py,代码行数:28,代码来源:compiler.py


示例8: compileFn

def compileFn(comp, name, form, orgform):
    locals, args, lastisargs, argsname = unpackArgs(form.first())

    comp.pushLocals(locals)
    if orgform.meta() is not None:
        line = orgform.meta()[LINE_KEY]
    else:
        line = 0
    code = [(SetLineno,line if line is not None else 0)]
    recurlabel = Label("recurLabel")
    recur = {"label": recurlabel,
             "args": args}
    code.append((recurlabel, None))
    comp.pushRecur(recur)
    code.extend(compileImplcitDo(comp, form.next()))
    comp.popRecur()

    code.append((RETURN_VALUE,None))
    comp.popLocals(locals)
    clist = comp.closureList()

    c = Code(code, comp.closureList(), args, lastisargs, False, True, str(Symbol.intern(comp.getNS().__name__, name.name)), "./clj/clojure/core.clj", 0, None)
    if not clist:
        c = new.function(c.to_code(), comp.ns.__dict__, name.name)

    return [(LOAD_CONST, c)]
开发者ID:AlexBaranosky,项目名称:clojure-py,代码行数:26,代码来源:compiler.py


示例9: test_callmethod_opcode

    def test_callmethod_opcode(self):
        """ Tests code generated by pypy-c compiled with CALL_METHOD
        bytecode
        """
        self.patch_opcodes('CALL_METHOD', 'LOOKUP_METHOD')
        try:
            class X:
                def m(self):
                    return 3

            def f():
                x = X()
                return x.m()

            # this code is generated by pypy-c when compiling above f
            pypy_code = 't\x00\x00\x83\x00\x00}\x00\x00|\x00\x00\xc9\x01\x00\xca\x00\x00S'
            new_c = self.monkey_patch_code(f.func_code, 3, 3, pypy_code, ('X', 'x', 'm'), ('x',))
            f2 = new.function(new_c, locals(), 'f')

            graph = self.codetest(f2)
            all_ops = self.all_operations(graph)
            assert all_ops['simple_call'] == 2
            assert all_ops['getattr'] == 1
        finally:
            self.unpatch_opcodes('CALL_METHOD', 'LOOKUP_METHOD')
开发者ID:Debug-Orz,项目名称:Sypy,代码行数:25,代码来源:test_objspace.py


示例10: compileFn

def compileFn(comp, name, form, orgform):
    locals, args, lastisargs, argsname = unpackArgs(form.first())

    for x in locals:
        comp.pushAlias(x, FnArgument(x))

    if orgform.meta() is not None:
        line = orgform.meta()[LINE_KEY]
    else:
        line = 0
    code = [(SetLineno,line if line is not None else 0)]
    if lastisargs:
        code.extend(cleanRest(argsname.name))

    recurlabel = Label("recurLabel")

    recur = {"label": recurlabel,
    "args": map(lambda x: comp.getAlias(symbol(x)).compileSet(comp), args)}

    code.append((recurlabel, None))
    comp.pushRecur(recur)
    code.extend(compileImplcitDo(comp, form.next()))
    comp.popRecur()
    code.append((RETURN_VALUE,None))
    comp.popAliases(locals)

    clist = map(lambda x: x.sym.name, comp.closureList())
    code = expandMetas(code, comp)
    c = Code(code, clist, args, lastisargs, False, True, str(symbol(comp.getNS().__name__, name.name)), comp.filename, 0, None)
    if not clist:
        c = new.function(c.to_code(), comp.ns.__dict__, name.name)

    return [(LOAD_CONST, c)], c
开发者ID:redalastor,项目名称:clojure-py,代码行数:33,代码来源:compiler.py


示例11: RegisterConfig

def RegisterConfig(name, *args):
    def y():
        pass

    source = """def __init__(self, a):
                        print "ACAAAAAAAAAA" """

    
    #compiled_code = compile(source, name, "single")

    code = compile(source, name, "single")

    nlocals = 10

    compiled_code = types.CodeType(1, nlocals, code.co_stacksize, code.co_flags,
    code.co_code, code.co_consts, code.co_names,
    code.co_varnames, code.co_filename,
    code.co_name,
    code.co_firstlineno, code.co_lnotab,
    code.co_freevars,
    code.co_cellvars)
    #compiled_code = y.func_code
    f = new.function(compiled_code, globals(), "init")
     
    print f("a")

    clase = new.classobj(name, (), {})

    im = new.instancemethod(f, name, ())

    setattr(clase, "__init__", im)    
    
    return clase
开发者ID:jorik041,项目名称:pycodin,代码行数:33,代码来源:dynamo.py


示例12: _function_named

def _function_named(fn, newname):
    try:
        fn.__name__ = newname
    except:
        fn = new.function(fn.func_code, fn.func_globals, newname,
                          fn.func_defaults, fn.func_closure)
    return fn
开发者ID:Frihet,项目名称:sqlalchemy-patches,代码行数:7,代码来源:compat.py


示例13: test_callmethod_opcode

    def test_callmethod_opcode(self):
        """ Tests code generated by pypy-c compiled with CALL_METHOD
        bytecode
        """
        flow_meth_names = flowcontext.FlowSpaceFrame.opcode_method_names
        pyframe_meth_names = PyFrame.opcode_method_names
        for name in ['CALL_METHOD', 'LOOKUP_METHOD']:
            num = bytecode_spec.opmap[name]
            locals()['old_' + name] = flow_meth_names[num]
            flow_meth_names[num] = pyframe_meth_names[num]
        try:
            class X:
                def m(self):
                    return 3

            def f():
                x = X()
                return x.m()

            # this code is generated by pypy-c when compiling above f
            pypy_code = 't\x00\x00\x83\x00\x00}\x00\x00|\x00\x00\xc9\x01\x00\xca\x00\x00S'
            new_c = self.monkey_patch_code(f.func_code, 3, 3, pypy_code, ('X', 'x', 'm'), ('x',))
            f2 = new.function(new_c, locals(), 'f')

            graph = self.codetest(f2)
            all_ops = self.all_operations(graph)
            assert all_ops['simple_call'] == 2
            assert all_ops['getattr'] == 1
        finally:
            for name in ['CALL_METHOD', 'LOOKUP_METHOD']:
                num = bytecode_spec.opmap[name]
                flow_meth_names[num] = locals()['old_' + name]
开发者ID:gorakhargosh,项目名称:pypy,代码行数:32,代码来源:test_objspace.py


示例14: compileMultiFn

def compileMultiFn(comp, name, form):
    s = form
    argdefs = []

    while s is not None:
        argdefs.append(MultiFn(comp, s.first()))
        s = s.next()
    argdefs = sorted(argdefs, lambda x, y: len(x.args) < len(y.args))
    if len(filter(lambda x: x.lastisargs, argdefs)) > 1:
        raise CompilerException("Only one function overload may have variable number of arguments", form)

    code = []
    if len(argdefs) == 1 and not argdefs[0].lastisargs:
        hasvararg = False
        argslist = argdefs[0].args
        code.extend(argdefs[0].bodycode)
    else:
        hasvararg = True
        argslist = ["__argsv__"]
        for x in argdefs:
            code.extend(x.argcode)
            code.extend(x.bodycode)

        code.append((LOAD_CONST, Exception))
        code.append((CALL_FUNCTION, 0))
        code.append((RAISE_VARARGS, 1))

    clist = map(lambda x: x.sym.name, comp.closureList())
    code = expandMetas(code, comp)
    c = Code(code, clist, argslist, hasvararg, False, True, str(symbol(comp.getNS().__name__, name.name)), comp.filename, 0, None)
    if not clist:
        c = new.function(c.to_code(), comp.ns.__dict__, name.name)
    return [(LOAD_CONST, c)], c
开发者ID:redalastor,项目名称:clojure-py,代码行数:33,代码来源:compiler.py


示例15: mergeFunctionMetadata

def mergeFunctionMetadata(f, g):
    """
    Overwrite C{g}'s name and docstring with values from C{f}.  Update
    C{g}'s instance dictionary with C{f}'s.

    To use this function safely you must use the return value. In Python 2.3,
    L{mergeFunctionMetadata} will create a new function. In later versions of
    Python, C{g} will be mutated and returned.

    @return: A function that has C{g}'s behavior and metadata merged from
        C{f}.
    """
    try:
        g.__name__ = f.__name__
    except TypeError:
        try:
            merged = new.function(
                g.func_code, g.func_globals,
                f.__name__, inspect.getargspec(g)[-1],
                g.func_closure)
        except TypeError:
            pass
    else:
        merged = g
    try:
        merged.__doc__ = f.__doc__
    except (TypeError, AttributeError):
        pass
    try:
        merged.__dict__.update(g.__dict__)
        merged.__dict__.update(f.__dict__)
    except (TypeError, AttributeError):
        pass
    merged.__module__ = f.__module__
    return merged
开发者ID:jml,项目名称:deferred,代码行数:35,代码来源:_util.py


示例16: maybe_bind

def maybe_bind(func, bindings):
    """Apply expression bindings to arguments, if applicable"""

    if not bindings or not hasattr(func, 'func_code'):
        return func     # no bindings or not a function

    args, varargs, varkw, defaults = inspect.getargspec(func) 
    if not args or isinstance(args[0], basestring):
        return func # no args or first arg isn't a tuple

    for arg in args[0]:
        if not isinstance(arg, basestring):  # nested tuple arg, not a binding
            return func

    for arg in args[0]:
        if arg in bindings:
            for arg in args[0]:
                if arg not in bindings:
                    raise TypeError("Missing binding for %r" % arg)
            break
    else:
        return func     # none of the tuple args are in the binding

    argtuple = Tuple([bindings[arg] for arg in args[0]])

    c = Code.from_spec(func.func_name, args[1:], varargs, varkw)
    f = new.function(
        c.code(), func.func_globals, func.func_name, func.func_defaults
    )
    f.func_code = c.code()  # make f's signature match func w/out tuple
    c.return_(call_thru(f, Const(func), [argtuple]))    # call to match that
    f.func_code = c.code()  # now include the actual body
    f.__predicate_bindings__ = bindings, func   # mark for later optimization

    return f
开发者ID:gustavo-gomez,项目名称:freezing-tyrion,代码行数:35,代码来源:predicates.py


示例17: makeDeclFuncts

    def makeDeclFuncts(self, keyList, classNames, classes):
        functs = dict()
        for key in keyList:

            className = classNames.get(key)
            functName = className + "Const"

            functStr = (
                "\
def "
                + functName
                + "(scanner,token):\
node= "
                + className
                + '(); node.type = "'
                + className
                + '"; node.value = token; return node'
            )
            functCo = compile(functStr, "", "exec")
            ns = {}
            exec functCo in ns
            funct = new.function(ns[functName].func_code, globals(), functName)
            globals()[functName] = funct
            functs[key] = functName

        return functs
开发者ID:maxywb,项目名称:OPPpy,代码行数:26,代码来源:Scanner.py


示例18: setup_a_rules_to_p_funcs

def setup_a_rules_to_p_funcs(ns):
    rules = []
    for name,val in ns.items():
        if name.startswith('a_'):
            name = name[2:]
            rule,action_maker = val
            # call all pre before all make_action, so that synth classes are
            # pre-defined (in pre methods) and can be used freely by make_actions
            action_maker.pre(name)
            rules.append((name,rule,action_maker))
            
    for name,rule,action_maker in rules:
        action = action_maker.make_action()
        name = 'p_%s' % name
        # cannot set __name__ on a function and spark uses func.__name__ to gather rule name so
        ns[name] = new.function(action.func_code,action.func_globals,name,action.func_defaults,action.func_closure)
        if hasattr(action,'_spec'): # copy _spec
            ns[name]._spec = action._spec
        if hasattr(action,'making'): # copy making
            ns[name].making = action.making
        ns[name].__doc__ = rule

    # add preprocessing, produced p_funcs expect a spec argument
    # wrap them appropriately
    def preprocess(self,rule,func):
        if hasattr(func,'_spec') and func._spec is not None:
            spec = func._spec
        else:
            spec = rule[1]
        return rule,lambda args: func(spec,args)

    ns['preprocess'] = preprocess
开发者ID:LPSAutomation,项目名称:IBM-Innovate-2012,代码行数:32,代码来源:java_parser.py


示例19: __init__

    def __init__(self, target, deep_decoration = True):
        """
        Init a decorator. "deep_decoration" activates a wrapping of the
        original methods. If true, direct calls to the inner object methods
        will go through all decorators. This is especially sensible, when the
        inner object calls methods of its own.
        """

        # the only datamember of a decorator
        self.__dict__['decoratee']  = target
        self.__dict__['dec_par'] = dict()

        # this is automatically forwarded to the inner decoratee
        target._outermost_decorator = self

        if deep_decoration and not isinstance(target, CRDecorator):
            # make the inner object decorator-aware
            # the mechanism is the same as if @decorator_sensitive would be
            # applied to each of the inner objects methods.

            # in some cases needed
            target._inner_decoratee = target

            # get methods
            members = getmembers(target)
            methods = [m for m in members if ismethod(m[1])]
            for m in methods:

                # wrap methods properly with decorator_sensitive(...)
                m_func = function(m[1].func_code, m[1].func_globals)
                m_func = decorator_sensitive(m_func)
                m_func = instancemethod(m_func, target)

                # do the monkey-'wrap'
                setattr(target, m[0], m_func)
开发者ID:RwthAachenIIIB,项目名称:UserCode,代码行数:35,代码来源:CRDecorator.py


示例20: breadth_first_traversal

def breadth_first_traversal( _old ):
    
    s = []
    
    def _savenode( *args, **kwargs ):
        s.append( (args,kwargs) )
    
    newglobal = _old.func_globals.copy()
    newglobal[_old.__name__] = _savenode
    
    _oldBF = new.function( _old.func_code, newglobal )
    
    def _new( *args, **kwargs ):
        
        s.append( (args,kwargs) )
        
        while( len(s)!=0 ):
            a, kwa = s.pop(0)
            _oldBF( *a, **kwa )
    
    _new._decorator = _old
    _new.__name__ = _old.__name__
    _new.__doc__  = _old.__doc__
    
    return _new
开发者ID:drmingdrmer,项目名称:py-aluminium,代码行数:25,代码来源:easytree.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python new.instance函数代码示例发布时间:2022-05-27
下一篇:
Python new.code函数代码示例发布时间: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