On Thu, 01 Sep 2005 21:25:20 -0500, D H <[EMAIL PROTECTED]> wrote: >talin at acm dot org wrote: >> Although I realize the perils of even suggesting polluting the Python >> namespace with a new keyword, I often think that it would be useful to >> consider defining an operator for testing whether or not an item is a >> member of a category. > >It's a good idea but not likely to be added to python, at least not til >python 3000 comes out with type checking. The default way is "if >isinstance(image, jpeg)". >Also there is "if image |isa| jpeg:" using one of the various python >hacks out there: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122 > >But since Python doesn't have interfaces or type checking today, there >really is not much need for isa or isinstance anyway, but you might use >hasattr or try/except instead: http://www.canonical.org/~kragen/isinstance/
I recently experimented with an ast-rewriting importer, and I suspect could set up a configurable importer that would recognize '|isa|' (or with any other legal binary op in place of '|'). Maybe '**' would stand out in "if image **isa** jpeg" and reduce processing since it's less commonly used than e.g., + or -. OTOH, the latter would permit unary operator definitions as well, e.g., "-inv- mx" could translate to mx**-1 meaning Sub((UnarySub(Name('inv')), Name('mx'))) int the ast is translated to opmod.inv(mx) replacing the above with CallFunc(Getattr(Name('opmod'), 'inv'), [Name('mx')], None, None) You could just write a module so that names to use would be given by [name for name in dir(opmod) if not name.startswith('_') and callable(getattr(opmod, name)] and then have the importer do that when given the module as config info, and look for the names, e.g., 'inv' in an ast subtree context as above, or for "left -isa- right" look for Sub((Sub((Name('left'), Name('isa'))), Name('right'))) and rewite it as CallFunc(Getattr(Name('opmod'), 'isa'), [Name('left'), Name('right')], None, None) My recent post was doing 'a/b' => safediv(a, b) in a similar fashion, which gives me the feeling that -xx- as custom infix operator would work for a lot of contexts. BTW, the ast for "left |isa| right" is Bitor([Name('left'), Name('isa'), Name('right')]) which probably makes it faster to recognize. Obviously subtrees not involving the specal op names would be ignored. I don't know if ast-rewriting on the fly during customizable import excites anyone, or if those who understand what I'm doing would just rather I didn't post about it "devant les enfants" ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list