type() and types

Matthew Dixon Cowles matt at mondoinfo.com
Wed Oct 4 21:48:45 EDT 2000


On Wed, 04 Oct 2000 18:31:36 -0700, Terry Hancock
<hancock at earthlink.net> wrote:

>I'm implementing a new object class in Python to do fuzzy logic, and
>for various reasons I need to check the type of variables to
>determine if they are fuzzy logic values.

>It seems like the "right" way to do this is to somehow provide type()
>the capability to do this, and this seems to be how some of the
>standard modules work (since they provide new types), but amongst
>"Learning Python" the "Python Reference Manual" and the "Python
>Library Reference" I'm not able to figure out how this is done.
>Maybe I'm just being thick, but I couldn't find anything about it.
>What am I missing?  Does anyone know how to do this?  TiA!

If you want to add new types to the language, you'll need to muck with
C. I suspect that the reason that doing that isn't emphasized is that
it's rarely needed. Would checking isinstance() give you the
information you need? Here's a trivial example:

>>> class fuzzy:
...   pass
... 
>>> f=fuzzy()
>>> isinstance(f,fuzzy)
1
>>> isinstance("wibble",fuzzy)
0

But in my own work, I find that I'm generally better off not doing
things like that. Here's why: When I want to check that something is
of a particular class or type, it's almost always because I want to
perform some operation on it. I find it's better to check directly
whether the thing supports the operation than to check to see if it's
the kind of thing that I know will support the operation. That way I
can use my code on other things that I haven't yet thought of but turn
out to support whaterver I'm trying to do. Python routinely does
things this way and it has turned out well. Here's a quote from the
comments at the top of the rfc822 module:

>This class can work with any input object that supports a readline
>method.  If the input object has seek and tell capability, the
>rewindbody method will work; also illegal lines will be pushed back
>onto the input stream.  If the input object lacks seek but has an
>`unread' method that can push back a line of input, Message will use
>that to push back illegal lines.  Thus this class can be used to
>parse messages coming from a buffered stream.

Of course, it may be that none of this is relevant to your problem.

Regards,
Matt



More information about the Python-list mailing list