[Tutor] Type Checking:/High-Jacking Reserved Words
Michael P. Reilly
arcege@shore.net
Mon, 5 Mar 2001 07:59:41 -0500 (EST)
> On Mon, Mar 05, 2001 at 11:26:19AM -0000, alan.gauld@bt.com wrote:
> > > I would welcome some comments from anyone as to the
> > > comparative advantages of the following
> > > > type(mystr) == types.StringType
> >
> > This works best if you are checkjing for type several
> > times since the import overhead only gets called once.
> >
> > > > type(mystr) == type("")
> >
> > This is better if you only do it once since the extra
> > function call is probably faster than importing the
> > type module.
>
> Since type has to return a Type itself, I bet it also imports the type
> module itself (or the equivalent in C). It's not just a function call, it
> has to decide what type 'mystr' is, and then it has to decide what type "" is.
Actually, no. There is an ob_type field in the PyObject structure (the
C data structure for all Python objects). This is what is returned by
the type() function. The types module will basically retrieve these
values for each built-in data type. The built-in type() function would
likely be much faster than a reference into a module.
> *fiddle with profiler*
>
> Hmm, oddly enough, the second is a lot faster, even if the import only
> happens once for 500,000 iterations. So much for reasoning about efficiency
> :).
>
> I still don't like the way 'type(mystr) == type("")' looks, and I don't
> think decisions like this should be made based on speed (after all, why not
> use C if you want to do premature optimization...), but whatever.
I agree. Myself, I find 'type(mystr) is types.StringType' and
'isinstance(mystr, types.StringType)' far more clear than 'type(mystr)
is type("")'
-Arcege
PS: The type objects are unique so using the identity (is, is not)
operators will be faster than the equivalence (==,!=,<>) operators.
And in terms of style, "is" is more clear than "==", for me anyway.
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------