本文整理汇总了Python中new.function方法的典型用法代码示例。如果您正苦于以下问题:Python new.function方法的具体用法?Python new.function怎么用?Python new.function使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类new
的用法示例。
在下文中一共展示了new.function方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: uniquer
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def uniquer(seq, idfun=None):
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
# A more efficient implementation of Alex's uniquer(), this avoids the
# idfun() argument and function-call overhead by assuming that all
# items in the sequence are hashable.
示例2: MD5collect
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def MD5collect(signatures):
"""
Collects a list of signatures into an aggregate signature.
signatures - a list of signatures
returns - the aggregate signature
"""
if len(signatures) == 1:
return signatures[0]
else:
return MD5signature(string.join(signatures, ', '))
# Wrap the intern() function so it doesn't throw exceptions if ineligible
# arguments are passed. The intern() function was moved into the sys module in
# Python 3.
示例3: makeStatBar
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def makeStatBar(width, maxPosition, doneChar = '=', undoneChar = '-', currentChar = '>'):
"""Creates a function that will return a string representing a progress bar.
"""
aValue = width / float(maxPosition)
def statBar(position, force = 0, last = ['']):
assert len(last) == 1, "Don't mess with the last parameter."
done = int(aValue * position)
toDo = width - done - 2
result = "[%s%s%s]" % (doneChar * done, currentChar, undoneChar * toDo)
if force:
last[0] = result
return result
if result == last[0]:
return ''
last[0] = result
return result
statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar
returned string is %d characters long, and the range goes from 0..%d.
The 'position' argument is where the '%s' will be drawn. If force is false,
'' will be returned instead if the resulting progress bar is identical to the
previously returned progress bar.
""" % (doneChar * 3, currentChar, undoneChar * 3, width, maxPosition, currentChar)
return statBar
示例4: spewer
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def spewer(frame, s, ignored):
"""A trace function for sys.settrace that prints every function or method call."""
from twisted.python import reflect
if frame.f_locals.has_key('self'):
se = frame.f_locals['self']
if hasattr(se, '__class__'):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print 'method %s of %s at %s' % (
frame.f_code.co_name, k, id(se)
)
else:
print 'function %s in %s, line %s' % (
frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno)
示例5: setIDFunction
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def setIDFunction(idFunction):
"""
Change the function used by L{unsignedID} to determine the integer id value
of an object. This is largely useful for testing to give L{unsignedID}
deterministic, easily-controlled behavior.
@param idFunction: A function with the signature of L{id}.
@return: The previous function being used by L{unsignedID}.
"""
global _idFunction
oldIDFunction = _idFunction
_idFunction = idFunction
return oldIDFunction
# A value about twice as large as any Python int, to which negative values
# from id() will be added, moving them into a range which should begin just
# above where positive values from id() leave off.
示例6: save_timeseries
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def save_timeseries(self, obj):
import scikits.timeseries.tseries as ts
func, reduce_args, state = obj.__reduce__()
if func != ts._tsreconstruct:
raise pickle.PicklingError('timeseries using unexpected reconstruction function %s' % str(func))
state = (1,
obj.shape,
obj.dtype,
obj.flags.fnc,
obj._data.tostring(),
ts.getmaskarray(obj).tostring(),
obj._fill_value,
obj._dates.shape,
obj._dates.__array__().tostring(),
obj._dates.dtype, #added -- preserve type
obj.freq,
obj._optinfo,
)
return self.save_reduce(_genTimeSeries, (reduce_args, state))
示例7: _modules_to_main
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def _modules_to_main(modList):
"""Force every module in modList to be placed into main"""
if not modList:
return
main = sys.modules['__main__']
for modname in modList:
if type(modname) is str:
try:
mod = __import__(modname)
except Exception, i: #catch all...
sys.stderr.write('warning: could not import %s\n. Your function may unexpectedly error due to this import failing; \
A version mismatch is likely. Specific error was:\n' % modname)
print_exec(sys.stderr)
else:
setattr(main,mod.__name__, mod)
else:
#REVERSE COMPATIBILITY FOR CLOUD CLIENT 1.5 (WITH EPD)
#In old version actual module was sent
setattr(main,modname.__name__, modname)
#object generators:
示例8: _make_skel_func
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def _make_skel_func(code, num_closures, base_globals = None):
""" Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty.
"""
#build closure (cells):
if not ctypes:
raise Exception('ctypes failed to import; cannot build function')
cellnew = ctypes.pythonapi.PyCell_New
cellnew.restype = ctypes.py_object
cellnew.argtypes = (ctypes.py_object,)
dummy_closure = tuple(map(lambda i: cellnew(None), range(num_closures)))
if base_globals is None:
base_globals = {}
base_globals['__builtins__'] = __builtins__
return types.FunctionType(code, base_globals,
None, None, dummy_closure)
# this piece of opaque code is needed below to modify 'cell' contents
示例9: mergeFunctionMetadata
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def mergeFunctionMetadata(f, g):
"""
Overwrite C{g}'s docstring and name with values from C{f}. Update
C{g}'s instance dictionary with C{f}'s.
"""
try:
g.__doc__ = f.__doc__
except (TypeError, AttributeError):
pass
try:
g.__dict__.update(f.__dict__)
except (TypeError, AttributeError):
pass
try:
g.__name__ = f.__name__
except TypeError:
try:
g = new.function(
g.func_code, g.func_globals,
f.__name__, inspect.getargspec(g)[-1],
g.func_closure)
except TypeError:
pass
return g
示例10: test_java_serialization_pyfunction
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def test_java_serialization_pyfunction(self):
# Not directly supported due to lack of general utility
# (globals will usually be in the function object in
# func_globals), and problems with unserialization
# vulnerabilities. Users can always subclass from PyFunction
# for specific cases, as seen in PyCascading
import new
def f():
return 6 * 7 + max(0, 1, 2)
# However, using the new module, it's possible to create a
# function with no globals, which means the globals will come
# from the current context
g = new.function(f.func_code, {}, "g")
# But still forbid Java deserialization of this function
# object. Use pickling or other support instead.
with self.assertRaises(UnsupportedOperationException):
roundtrip_serialization(g)
示例11: render_tree
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def render_tree(root, child_func, prune=0, margin=[0], visited={}):
"""
Render a tree of nodes into an ASCII tree view.
root - the root node of the tree
child_func - the function called to get the children of a node
prune - don't visit the same node twice
margin - the format of the left margin to use for children of root.
1 results in a pipe, and 0 results in no pipe.
visited - a dictionary of visited nodes in the current branch if not prune,
or in the whole tree if prune.
"""
rname = str(root)
children = child_func(root)
retval = ""
for pipe in margin[:-1]:
if pipe:
retval = retval + "| "
else:
retval = retval + " "
if rname in visited:
return retval + "+-[" + rname + "]\n"
retval = retval + "+-" + rname + "\n"
if not prune:
visited = copy.copy(visited)
visited[rname] = 1
for i in range(len(children)):
margin.append(i<len(children)-1)
retval = retval + render_tree(children[i], child_func, prune, margin, visited
)
margin.pop()
return retval
示例12: RegGetValue
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def RegGetValue(root, key):
"""This utility function returns a value in the registry
without having to open the key first. Only available on
Windows platforms with a version of Python that can read the
registry. Returns the same thing as
SCons.Util.RegQueryValueEx, except you just specify the entire
path to the value, and don't have to bother opening the key
first. So:
Instead of:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion')
out = SCons.Util.RegQueryValueEx(k,
'ProgramFilesDir')
You can write:
out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
"""
# I would use os.path.split here, but it's not a filesystem
# path...
p = key.rfind('\\') + 1
keyp = key[:p-1] # -1 to omit trailing slash
val = key[p:]
k = RegOpenKeyEx(root, keyp)
return RegQueryValueEx(k,val)
示例13: make_path_relative
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def make_path_relative(path):
""" makes an absolute path name to a relative pathname.
"""
if os.path.isabs(path):
drive_s,path = os.path.splitdrive(path)
import re
if not drive_s:
path=re.compile("/*(.*)").findall(path)[0]
else:
path=path[1:]
assert( not os.path.isabs( path ) ), path
return path
# The original idea for AddMethod() and RenameFunction() come from the
# following post to the ActiveState Python Cookbook:
#
# ASPN: Python Cookbook : Install bound methods in an instance
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613
#
# That code was a little fragile, though, so the following changes
# have been wrung on it:
#
# * Switched the installmethod() "object" and "function" arguments,
# so the order reflects that the left-hand side is the thing being
# "assigned to" and the right-hand side is the value being assigned.
#
# * Changed explicit type-checking to the "try: klass = object.__class__"
# block in installmethod() below so that it still works with the
# old-style classes that SCons uses.
#
# * Replaced the by-hand creation of methods and functions with use of
# the "new" module, as alluded to in Alex Martelli's response to the
# following Cookbook post:
#
# ASPN: Python Cookbook : Dynamically added methods to a class
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
示例14: AddMethod
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def AddMethod(object, function, name = None):
"""
Adds either a bound method to an instance or an unbound method to
a class. If name is ommited the name of the specified function
is used by default.
Example:
a = A()
def f(self, x, y):
self.z = x + y
AddMethod(f, A, "add")
a.add(2, 4)
print a.z
AddMethod(lambda self, i: self.l[i], a, "listIndex")
print a.listIndex(5)
"""
import new
if name is None:
name = function.__name__
else:
function = RenameFunction(function, name)
try:
klass = object.__class__
except AttributeError:
# "object" is really a class, so it gets an unbound method.
object.__dict__[name] = new.instancemethod(function, None, object)
else:
# "object" is really an instance, so it gets a bound method.
object.__dict__[name] = new.instancemethod(function, object, klass)
示例15: get_commands
# 需要导入模块: import new [as 别名]
# 或者: from new import function [as 别名]
def get_commands(self):
if self._command_list is None:
hashfilter = {}
for name in filter(self._command_filt, dir(self)):
## this filters out aliases (same function id)
meth = getattr(self, name)
hashfilter[id(meth.im_func)] = meth.im_func.func_name
self._command_list = hashfilter.values()
self._command_list.sort()
return self._command_list
# user visible commands are methods that don't have a leading underscore,
# and do have a docstring.