[pylucene-dev] isinstance, instance_, cast_

Andi Vajda vajda at osafoundation.org
Wed Nov 14 09:48:43 PST 2007


On Wed, 14 Nov 2007, Pete wrote:

> So I'm starting to get my head around instance_/cast_ ...  Basically,
> sometimes Java sees an object as a less-specific type than it actually is,
> and being a static language, the attr/method names available are those of the
> less-specific type.
>
> For example:
> In [3]: q=QueryParser('pants', StandardAnalyzer()).parse('shirts AND -shoes')
> In [4]: q
> Out[4]: <Query: +pants:shirts -pants:shoes>
> In [5]: BooleanQuery.instance_(q)
> Out[5]: True
> In [6]: q.getClauses()
> <type 'exceptions.AttributeError'>: 'Query' object has no
> attribute 'getClauses'
> In [7]: bq=BooleanQuery.cast_(q)
> In [8]: bq.getClauses()
> Out[8]: [<BooleanClause: +pants:shirts>, <BooleanClause: -pants:shoes>]
>
> While this is probably perfectly sensible to a Java/C++ programmer, as a
> Python coder this behavior is somewhat foreign.  Hopefully the above example
> will help make it clearer - the one in the README wasn't quite clear to me.

Yep. This can only get better once the Java Lucene code switches to Java 1.5 
and starts using annotations. That way, a Collection type or an Iteration type 
can be wrapped with something more specific than Collection or Object. For the 
time being though, I'm afraid this is the way it is. (I'd also need to improve 
JCC to heed annotations, which remains to be implemented).

> My question is: when should we use isinstance(obj, Klass) vs.
> Klass.instance_(obj)?  From below, it looks like python's isinstance can look
> up the Java class hierarchy but not down.  As a general rule, should we
> always be using Klass.instance_ for such tests?  Will this work correctly
> with pure-python types / Python subclasses of Java classes?

PyLucene's Python objects are not direct instances of the Java ones, they're 
wrappers. When you're calling isinstance() you're checking the class of the 
wrapper object, not that of the wrappee.

The instance_() method on a wrapper checks the class of the wrappee.
In other words, if PyLucene.Query is actually wrapping a Java Lucene 
BooleanQuery, the wrapper is still only a Query, but 
PyLucene.BooleanQuery,instance_() is going to be True.

Andi..



More information about the pylucene-dev mailing list