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