Python new.instancemethod() Examples
The following are 30
code examples of new.instancemethod().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
new
, or try the search function
.
Example #1
Source File: jelly.py From BitTorrent with GNU General Public License v3.0 | 7 votes |
def _unjelly_method(self, rest): ''' (internal) unjelly a method ''' im_name = rest[0] im_self = self.unjelly(rest[1]) im_class = self.unjelly(rest[2]) if type(im_class) is not types.ClassType: raise InsecureJelly("Method found with non-class class.") if im_class.__dict__.has_key(im_name): if im_self is None: im = getattr(im_class, im_name) elif isinstance(im_self, NotKnown): im = _InstanceMethod(im_name, im_self, im_class) else: im = instancemethod(im_class.__dict__[im_name], im_self, im_class) else: raise 'instance method changed' return im
Example #2
Source File: pyversion.py From locality-sensitive-hashing with MIT License | 6 votes |
def force_unicode(s, encoding='UTF-8'): return str(s) # new.instancemethod() is obsolete for new-style classes (Python 3.x) # We need to use descriptor methods instead.
Example #3
Source File: jelly.py From python-for-android with Apache License 2.0 | 6 votes |
def _unjelly_method(self, rest): """ (internal) Unjelly a method. """ im_name = rest[0] im_self = self.unjelly(rest[1]) im_class = self.unjelly(rest[2]) if type(im_class) is not types.ClassType: raise InsecureJelly("Method found with non-class class.") if im_name in im_class.__dict__: if im_self is None: im = getattr(im_class, im_name) elif isinstance(im_self, NotKnown): im = _InstanceMethod(im_name, im_self, im_class) else: im = instancemethod(im_class.__dict__[im_name], im_self, im_class) else: raise TypeError('instance method changed') return im
Example #4
Source File: CLI.py From pycopia with Apache License 2.0 | 6 votes |
def get_generic_cmd(obj, ui, cliclass=GenericCLI, aliases=None, gbl=None): """get a GenericCLI (or other) command set wrapping any class instance object. The wrapped objects public methods have CLI command counterparts automatically created.""" import new from pycopia.methodholder import MethodHolder cmd = cliclass(ui, aliases) if gbl is None: gbl = globals() hashfilter = {} for name in _get_methodnames(obj): if hasattr(cmd, name): continue # don't override already defined methods # all this mess does is introspect the object methods and map it to a CLI # object method of the same name, with a docstring showing the attributes # and their default values, and the actual code mirroring the # _generic_call method in the GenericCLI class. else: obj_meth = getattr(obj, name) if id(obj_meth.__func__) in hashfilter: # filter out aliases continue else: hashfilter[id(obj_meth.__func__)] = True mh = MethodHolder(obj_meth) doc = "%s *\n%s" % (mh, obj_meth.__doc__ or "") code = cliclass._generic_call.func_code nc = new.code(code.co_argcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, (doc,)+code.co_consts[1:], # replace docstring code.co_names, code.co_varnames, code.co_filename, code.co_name, code.co_firstlineno, code.co_lnotab) f = new.function(nc, gbl, name) m = new.instancemethod(f, cmd, cliclass) setattr(cmd, name, m) cmd._setup(obj, "Object:%s> " % (obj.__class__.__name__,)) return cmd
Example #5
Source File: recipe-52192.py From code with MIT License | 5 votes |
def addStr(anInstance): anInstance.__str__ = new.instancemethod(__str__, anInstance, anInstance.__class__) # Test it
Example #6
Source File: explorer.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def install(self, methodIdentifier): """Install myself on my instance in place of this method. """ oldMethod = getattr(self.instance, methodIdentifier, None) # XXX: this conditional probably isn't effective. if oldMethod is not self: # avoid triggering __setattr__ self.instance.__dict__[methodIdentifier] = ( new.instancemethod(self, self.instance, self.instance.__class__)) self.oldMethod = (methodIdentifier, oldMethod)
Example #7
Source File: crefutil.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def __setitem__(self, n, obj): assert n == 0, "only zero index allowed" if not isinstance(obj, NotKnown): self.resolveDependants(instancemethod(self.my_class.__dict__[self.name], obj, self.my_class))
Example #8
Source File: styles.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def unpickleMethod(im_name, im_self, im_class): 'support function for copy_reg to unpickle method refs' try: unbound = getattr(im_class,im_name) if im_self is None: return unbound bound=instancemethod(unbound.im_func, im_self, im_class) return bound except AttributeError: log.msg("Method",im_name,"not on class",im_class) assert im_self is not None,"No recourse: no instance to guess from." # Attempt a common fix before bailing -- if classes have # changed around since we pickled this method, we may still be # able to get it by looking on the instance's current class. unbound = getattr(im_self.__class__,im_name) log.msg("Attempting fixup with",unbound) if im_self is None: return unbound bound=instancemethod(unbound.im_func, im_self, im_self.__class__) return bound
Example #9
Source File: explorer.py From python-for-android with Apache License 2.0 | 5 votes |
def install(self, methodIdentifier): """Install myself on my instance in place of this method. """ oldMethod = getattr(self.instance, methodIdentifier, None) # XXX: this conditional probably isn't effective. if oldMethod is not self: # avoid triggering __setattr__ self.instance.__dict__[methodIdentifier] = ( new.instancemethod(self, self.instance, self.instance.__class__)) self.oldMethod = (methodIdentifier, oldMethod)
Example #10
Source File: crefutil.py From python-for-android with Apache License 2.0 | 5 votes |
def __setitem__(self, n, obj): assert n == 0, "only zero index allowed" if not isinstance(obj, NotKnown): self.resolveDependants(instancemethod(self.my_class.__dict__[self.name], obj, self.my_class))
Example #11
Source File: styles.py From python-for-android with Apache License 2.0 | 5 votes |
def unpickleMethod(im_name, im_self, im_class): 'support function for copy_reg to unpickle method refs' try: unbound = getattr(im_class,im_name) if im_self is None: return unbound bound=instancemethod(unbound.im_func, im_self, im_class) return bound except AttributeError: log.msg("Method",im_name,"not on class",im_class) assert im_self is not None,"No recourse: no instance to guess from." # Attempt a common fix before bailing -- if classes have # changed around since we pickled this method, we may still be # able to get it by looking on the instance's current class. unbound = getattr(im_self.__class__,im_name) log.msg("Attempting fixup with",unbound) if im_self is None: return unbound bound=instancemethod(unbound.im_func, im_self, im_self.__class__) return bound
Example #12
Source File: weakmethod.py From Tickeys-linux with MIT License | 5 votes |
def __call__(self): '''Return a new bound-method like the original, or the original function if it was just a function or unbound method. Returns None if the original object doesn't exist. ''' if self.is_dead(): return None if self._obj is not None: return new.instancemethod(self._func, self._obj(), self._class) else: # we don't have an instance: return just the function return self._func
Example #13
Source File: weakmethod.py From Tickeys-linux with MIT License | 5 votes |
def __call__(self): '''Return a new bound-method like the original, or the original function if it was just a function or unbound method. Returns None if the original object doesn't exist. ''' if self.is_dead(): return None if self._obj is not None: return new.instancemethod(self._func, self._obj(), self._class) else: # we don't have an instance: return just the function return self._func
Example #14
Source File: test_cache.py From ccs-calendarserver with Apache License 2.0 | 5 votes |
def setUp(self): TestCase.setUp(self) self.memcache = InMemoryMemcacheProtocol() self.ccn = MemcacheChangeNotifier( StubURLResource(':memory:'), cachePool=self.memcache) self.ccn._newCacheToken = instancemethod(_newCacheToken, self.ccn, MemcacheChangeNotifier)
Example #15
Source File: recipe-229472.py From code with MIT License | 5 votes |
def curry1(func, arg): return new.instancemethod(func, arg, object)
Example #16
Source File: recipe-52194.py From code with MIT License | 5 votes |
def addStr(anInstance): anInstance.__str__ = new.instancemethod(__str__, anInstance, anInstance.__class__) # Test it
Example #17
Source File: Memoize.py From pivy with ISC License | 5 votes |
def __init__(cls, name, bases, cls_dict): super(Memoized_Metaclass, cls).__init__(name, bases, cls_dict) for counter in cls_dict.get('memoizer_counters', []): method_name = counter.method_name counter.name = cls.__name__ + '.' + method_name counter.underlying_method = cls_dict[method_name] replacement_method = new.instancemethod(counter, None, cls) setattr(cls, method_name, replacement_method)
Example #18
Source File: test_result.py From browserscope with Apache License 2.0 | 5 votes |
def AddAdjustResults(test_set): def AdjustResults(self, results): for values in results.values(): # Add the raw value to be expando'd and store a munged value in score. values['expando'] = values['raw_score'] values['raw_score'] = int(round(values['raw_score'] / 2.0)) return results test_set.AdjustResults = new.instancemethod( AdjustResults, test_set, test_set.__class__)
Example #19
Source File: pyversion.py From locality-sensitive-hashing with MIT License | 5 votes |
def make_instancemethod(function, instance): return new.instancemethod(function.im_func, instance, instance.__class__)
Example #20
Source File: pyversion.py From Computable with MIT License | 5 votes |
def make_instancemethod(function, instance): return new.instancemethod(function.im_func, instance, instance.__class__)
Example #21
Source File: Memoize.py From pivy with ISC License | 5 votes |
def __init__(cls, name, bases, cls_dict): cls.use_metaclass = 1 def fake_method(self): pass new.instancemethod(fake_method, None, cls)
Example #22
Source File: middleware.py From crowdata with MIT License | 5 votes |
def _do_set_current_user(user_fun): setattr(_thread_locals, USER_ATTR_NAME, instancemethod(user_fun, _thread_locals, type(_thread_locals)))
Example #23
Source File: Util.py From pivy with ISC License | 5 votes |
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)
Example #24
Source File: CLI.py From pycopia with Apache License 2.0 | 5 votes |
def get_generic_cmd(obj, ui, cliclass=GenericCLI, aliases=None, gbl=None): """get a GenericCLI (or other) command set wrapping any class instance object. The wrapped objects public methods have CLI command counterparts automatically created.""" import new from methodholder import MethodHolder cmd = cliclass(ui, aliases) if gbl is None: gbl = globals() hashfilter = {} for name in _get_methodnames(obj): if hasattr(cmd, name): continue # don't override already defined methods # all this mess does is introspect the object methods and map it to a CLI # object method of the same name, with a docstring showing the attributes # and their default values, and the actual code mirroring the # _generic_call method in the GenericCLI class. else: obj_meth = getattr(obj, name) if id(obj_meth.im_func) in hashfilter: # filter out aliases continue else: hashfilter[id(obj_meth.im_func)] = True mh = MethodHolder(obj_meth) doc = "%s *\n%s" % (mh, obj_meth.__doc__ or "") code = cliclass._generic_call.func_code nc = new.code(code.co_argcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, (doc,)+code.co_consts[1:], # replace docstring code.co_names, code.co_varnames, code.co_filename, code.co_name, code.co_firstlineno, code.co_lnotab) f = new.function(nc, gbl, name) m = new.instancemethod(f, cmd, cliclass) setattr(cmd, name, m) cmd._setup(obj, "Object:%s> " % (obj.__class__.__name__,)) return cmd
Example #25
Source File: POMparse.py From pycopia with Apache License 2.0 | 5 votes |
def get_parser(document=None, namespaces=0, validate=0, external_ges=1, logfile=None, doc_factory=POM.new_document): import xml if hasattr(xml, "use_pyxml"): xml.use_pyxml() import xml.sax.sax2exts import xml.sax.handler import new handler = ContentHandler(document, doc_factory=doc_factory, logfile=logfile) errorhandler = ErrorHandler(logfile) # create parser parser = xml.sax.sax2exts.XMLParserFactory.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, namespaces) parser.setFeature(xml.sax.handler.feature_validation, validate) parser.setFeature(xml.sax.handler.feature_external_ges, external_ges) parser.setFeature(xml.sax.handler.feature_external_pes, 0) parser.setFeature(xml.sax.handler.feature_string_interning, 1) # set handlers parser.setContentHandler(handler) parser.setDTDHandler(handler) parser.setEntityResolver(handler) parser.setErrorHandler(errorhandler) # since the xml API provides some generic parser I can't just # subclass I have to "patch" the object in-place with this trick. # This is to a) make the API compatible with the HTMLParser, and b) # allow specifing the encoding and other headers in the request. parser.parse_orig = parser.parse def parse(self, url, data=None, encoding=POM.DEFAULT_ENCODING, useragent=None, accept=None): from pycopia.WWW import urllibplus fo = urllibplus.urlopen(url, data, encoding, useragent=useragent, accept=accept) if logfile: from pycopia import UserFile fo = UserFile.FileWrapper(fo, logfile=logfile) return self.parse_orig(fo) parser.parse = new.instancemethod(parse, parser, parser.__class__) return parser
Example #26
Source File: compat.py From pyFileFixity with MIT License | 5 votes |
def instancemethod(*args): return args[0]
Example #27
Source File: recipe-572213.py From code with MIT License | 5 votes |
def save_instancemethod(self, obj): """ Save an instancemethod object """ # Instancemethods are re-created each time they are accessed so this will not be memoized args = (obj.im_func, obj.im_self, obj.im_class) self.save_reduce(new.instancemethod, args)
Example #28
Source File: rbf.py From Splunking-Crime with GNU Affero General Public License v3.0 | 4 votes |
def _init_function(self, r): if isinstance(self.function, str): self.function = self.function.lower() _mapped = {'inverse': 'inverse_multiquadric', 'inverse multiquadric': 'inverse_multiquadric', 'thin-plate': 'thin_plate'} if self.function in _mapped: self.function = _mapped[self.function] func_name = "_h_" + self.function if hasattr(self, func_name): self._function = getattr(self, func_name) else: functionlist = [x[3:] for x in dir(self) if x.startswith('_h_')] raise ValueError("function must be a callable or one of " + ", ".join(functionlist)) self._function = getattr(self, "_h_"+self.function) elif callable(self.function): allow_one = False if hasattr(self.function, 'func_code') or \ hasattr(self.function, '__code__'): val = self.function allow_one = True elif hasattr(self.function, "im_func"): val = get_method_function(self.function) elif hasattr(self.function, "__call__"): val = get_method_function(self.function.__call__) else: raise ValueError("Cannot determine number of arguments to function") argcount = get_function_code(val).co_argcount if allow_one and argcount == 1: self._function = self.function elif argcount == 2: if sys.version_info[0] >= 3: self._function = self.function.__get__(self, Rbf) else: import new self._function = new.instancemethod(self.function, self, Rbf) else: raise ValueError("Function argument must take 1 or 2 arguments.") a0 = self._function(r) if a0.shape != r.shape: raise ValueError("Callable must take array and return array of the same shape") return a0
Example #29
Source File: explorer.py From python-for-android with Apache License 2.0 | 4 votes |
def watchObject(self, object, identifier, callback): """Watch the given object. Whenever I think the object might have changed, I'll send an ObjectLink of it to the callback. The identifier argument is used to generate identifiers for objects which are members of this one. """ if type(object) is not types.InstanceType: raise TypeError, "Sorry, can only place a watch on Instances." # uninstallers = [] dct = {} reflect.addMethodNamesToDict(object.__class__, dct, '') for k in object.__dict__.keys(): dct[k] = 1 members = dct.keys() clazzNS = {} clazz = new.classobj('Watching%s%X' % (object.__class__.__name__, id(object)), (_MonkeysSetattrMixin, object.__class__,), clazzNS) clazzNS['_watchEmitChanged'] = new.instancemethod( lambda slf, i=identifier, b=self, cb=callback: cb(b.browseObject(slf, i)), None, clazz) # orig_class = object.__class__ object.__class__ = clazz for name in members: m = getattr(object, name) # Only hook bound methods. if ((type(m) is types.MethodType) and (m.im_self is not None)): # What's the use of putting watch monkeys on methods # in addition to __setattr__? Well, um, uh, if the # methods modify their attributes (i.e. add a key to # a dictionary) instead of [re]setting them, then # we wouldn't know about it unless we did this. # (Is that convincing?) monkey = _WatchMonkey(object) monkey.install(name) # uninstallers.append(monkey.uninstall) # XXX: This probably prevents these objects from ever having a # zero refcount. Leak, Leak! ## self.watchUninstallers[object] = uninstallers
Example #30
Source File: rbf.py From GraphicDesignPatternByPython with MIT License | 4 votes |
def _init_function(self, r): if isinstance(self.function, str): self.function = self.function.lower() _mapped = {'inverse': 'inverse_multiquadric', 'inverse multiquadric': 'inverse_multiquadric', 'thin-plate': 'thin_plate'} if self.function in _mapped: self.function = _mapped[self.function] func_name = "_h_" + self.function if hasattr(self, func_name): self._function = getattr(self, func_name) else: functionlist = [x[3:] for x in dir(self) if x.startswith('_h_')] raise ValueError("function must be a callable or one of " + ", ".join(functionlist)) self._function = getattr(self, "_h_"+self.function) elif callable(self.function): allow_one = False if hasattr(self.function, 'func_code') or \ hasattr(self.function, '__code__'): val = self.function allow_one = True elif hasattr(self.function, "im_func"): val = get_method_function(self.function) elif hasattr(self.function, "__call__"): val = get_method_function(self.function.__call__) else: raise ValueError("Cannot determine number of arguments to function") argcount = get_function_code(val).co_argcount if allow_one and argcount == 1: self._function = self.function elif argcount == 2: if sys.version_info[0] >= 3: self._function = self.function.__get__(self, Rbf) else: import new self._function = new.instancemethod(self.function, self, Rbf) else: raise ValueError("Function argument must take 1 or 2 arguments.") a0 = self._function(r) if a0.shape != r.shape: raise ValueError("Callable must take array and return array of the same shape") return a0