我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.MethodType()。
def addMsgHandler(self, address, callback): """Register a handler for an OSC-address - 'address' is the OSC address-string. the address-string should start with '/' and may not contain '*' - 'callback' is the function called for incoming OSCMessages that match 'address'. The callback-function will be called with the same arguments as the 'msgPrinter_handler' below """ for chk in '*?,[]{}# ': if chk in address: raise OSCServerError("OSC-address string may not contain any characters in '*?,[]{}# '") if type(callback) not in (types.FunctionType, types.MethodType): raise OSCServerError("Message callback '%s' is not callable" % repr(callback)) if address != 'default': address = '/' + address.strip('/') self.callbacks[address] = callback
def __init__(self): cache = {} self.not_in_cache = not_in_cache = object() def get(self, key): return cache.get(key, not_in_cache) def set(self, key, value): cache[key] = value def clear(self): cache.clear() self.get = types.MethodType(get, self) self.set = types.MethodType(set, self) self.clear = types.MethodType(clear, self)
def __init__(self, size): self.not_in_cache = not_in_cache = object() cache = _OrderedDict() def get(self, key): return cache.get(key, not_in_cache) def set(self, key, value): cache[key] = value if len(cache) > size: cache.popitem(False) def clear(self): cache.clear() self.get = types.MethodType(get, self) self.set = types.MethodType(set, self) self.clear = types.MethodType(clear, self)
def __init__(self, size): self.not_in_cache = not_in_cache = object() cache = {} key_fifo = collections.deque([], size) def get(self, key): return cache.get(key, not_in_cache) def set(self, key, value): cache[key] = value if len(cache) > size: cache.pop(key_fifo.popleft(), None) key_fifo.append(key) def clear(self): cache.clear() key_fifo.clear() self.get = types.MethodType(get, self) self.set = types.MethodType(set, self) self.clear = types.MethodType(clear, self) # argument cache for optimizing repeated calls when backtracking through recursive expressions
def __init__(self): cache = {} self.not_in_cache = not_in_cache = object() def get(self, key): return cache.get(key, not_in_cache) def set(self, key, value): cache[key] = value def clear(self): cache.clear() def cache_len(self): return len(cache) self.get = types.MethodType(get, self) self.set = types.MethodType(set, self) self.clear = types.MethodType(clear, self) self.__len__ = types.MethodType(cache_len, self)
def validate_error_func(self): if self.error_func: if isinstance(self.error_func,types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = 1 return eline = func_code(self.error_func).co_firstlineno efile = func_code(self.error_func).co_filename self.files[efile] = 1 if (func_code(self.error_func).co_argcount != 1+ismethod): self.log.error("%s:%d: p_error() requires 1 argument",efile,eline) self.error = 1 # Get the tokens map
def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if name[:2] != 'p_': continue if name == 'p_error': continue if isinstance(item,(types.FunctionType,types.MethodType)): line = func_code(item).co_firstlineno file = func_code(item).co_filename p_functions.append((line,file,name,item.__doc__)) # Sort all of the actions by line number p_functions.sort() self.pfuncs = p_functions # Validate all of the p_functions
def set_action(self, action, *args): """Set action and arguments to run in triggered time :param action: function path as anction :type action: str :param args: function arguments :type args: list or tuple """ if isinstance(action, (types.FunctionType, types.MethodType)): self.action = action else: action_module = '.'.join(action.split('.')[:-1]) action_module = importlib.import_module(action_module) action = action.split('.')[-1] self.action = getattr(action_module, action) self.action_args = args
def add_network_methods(target): ''' Attach extension methods to an object that represents a Veneer network. Note: The 'network_' prefix will be removed from method names. target: Veneer network object to attach extension methods to. ''' import veneer.extensions as extensions # Import self to inspect available functions # Generate dict of {function name: function}, skipping this function this_func_name = sys._getframe().f_code.co_name funcs = inspect.getmembers(extensions, inspect.isfunction) funcs = dict((func_name, func) for func_name, func in funcs if func_name != this_func_name ) # Assign functions to target, removing the 'network_' prefix for f_name, f in funcs.items(): if f_name.startswith('network_'): f_name = f_name.replace('network_', '') setattr(target, f_name, MethodType(f, target))
def latestVersionOf(self, anObject): """Get the latest version of an object. This can handle just about anything callable; instances, functions, methods, and classes. """ t = type(anObject) if t == types.FunctionType: return latestFunction(anObject) elif t == types.MethodType: if anObject.im_self is None: return getattr(anObject.im_class, anObject.__name__) else: return getattr(anObject.im_self, anObject.__name__) elif t == types.InstanceType: # Kick it, if it's out of date. getattr(anObject, 'nothing', None) return anObject elif t == types.ClassType: return latestClass(anObject) else: log.msg('warning returning anObject!') return anObject
def lookupFunction(self, name): """ Return a callable to invoke when executing the named command. @param name: the normalized name (from the wire) of the command. @return: a function that takes one argument (a Box) and returns a box, for handling the command identified by the given name. """ # Try to find a high-level method to invoke, and if we can't find one, # fall back to a low-level one. cd = self._commandDispatch if name in cd: commandClass, responderFunc = cd[name] responderMethod = types.MethodType(responderFunc, self, self.__class__) return self._wrapWithSerialization(responderMethod, commandClass) # Fall back to simplistic command dispatching - this uses only strings, # not encoded/decoded values. fName = self.baseDispatchPrefix + (name.upper()) return getattr(self, fName, None)
def __init__(self, instance, identifier): Explorer.__init__(self, instance, identifier) members = {} methods = {} for i in dir(instance): # TODO: Make screening of private attributes configurable. if i[0] == '_': continue mIdentifier = string.join([identifier, i], ".") member = getattr(instance, i) mType = type(member) if mType is types.MethodType: methods[i] = explorerPool.getExplorer(member, mIdentifier) else: members[i] = explorerPool.getExplorer(member, mIdentifier) self.klass = explorerPool.getExplorer(instance.__class__, self.identifier + '.__class__') self.data = members self.methods = methods
def __init__(self, environment, parent, name, blocks): self.parent = parent self.vars = {} self.environment = environment self.eval_ctx = EvalContext(self.environment, name) self.exported_vars = set() self.name = name # create the initial mapping of blocks. Whenever template inheritance # takes place the runtime will update this mapping with the new blocks # from the template. self.blocks = dict((k, [v]) for k, v in iteritems(blocks)) # In case we detect the fast resolve mode we can set up an alias # here that bypasses the legacy code logic. if self._fast_resolve_mode: self.resolve_or_missing = MethodType(resolve_or_missing, self)
def assign_mapper(class_, *args, **params): params.setdefault("is_primary", True) if not isinstance(getattr(class_, '__init__'), types.MethodType): def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) class_.__init__ = __init__ m = mapper(class_, *args, **params) class_.mapper = m class_.get = m.get class_.select = m.select class_.select_by = m.select_by class_.selectone = m.selectone class_.get_by = m.get_by def commit(self): objectstore.commit(self) def delete(self): objectstore.delete(self) class_.commit = commit class_.delete = delete
def _monkey_patch_ipython(self): # The user may want to access the NS 3 simulation state, but # NS 3 is not thread safe, so it could cause serious problems. # To work around this, monkey-patch IPython to automatically # acquire and release the simulation lock around each code # that is executed. original_runcode = __IPYTHON__.runcode def runcode(ip, *args): #print "lock" self.simulation.lock.acquire() try: return original_runcode(*args) finally: #print "unlock" self.simulation.lock.release() import types __IPYTHON__.runcode = types.MethodType(runcode, __IPYTHON__)