本文整理汇总了Python中new.function函数的典型用法代码示例。如果您正苦于以下问题:Python function函数的具体用法?Python function怎么用?Python function使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了function函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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"
示例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)
示例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
示例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))
示例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
示例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)]
示例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)]
示例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')
示例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
示例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
示例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
示例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]
示例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
示例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