Re: myfile.py: a Class wrapper for file objects & prompting readlines()

Guido.van.Rossum@cwi.nl
Thu, 03 Mar 1994 10:31:36 +0100

(me:)
> > (I wonder if I should've made a distinction between these and, say,
> > __init__ and __del__ which are perfectly legal to use...)
(Tim:)
> I think the distinction is clear: __xxx__ is fine to use if _you're_ the
> one who binds its name (users define __init__, __del__, etc). But
> referring to __xxx__ is dubious style if Python binds the name by magic
> (covering __class__, __dict__, __bases__, __name__, and, like it or not,
> __methods__).
>
> The only way I _routinely_ break those guidelines is when I need to know
> whether an object belongs to a specific user-defined class. I don't know
> a better way to do that than
>
> if type(object) is type(_Some_UserDefinedClassInstance) and \
> object.__class__ is TheSpecificUserDefinedClassOfInterest:
> # object is an instance of TheSpecificUserDefinedClassOfInterest

The only reason why you test for type(object) is that you want to be
sure that object.__class__ doesn't raise an exception. Presuming you
don't want to use a try statement, how about writing it like this:

! if hasattr(object, '__class__') and \
! object.__class__ is TheSpecificUserDefinedClassOfInterest:
! # object is an instance of TheSpecificUserDefinedClassOfInterest

I know very few ways to cheat with this (e.g. you can't give a *class*
object a __class__ attribute -- the only way would be for an extension
written in C to define an object type with a __class__ attribute that
might be a class but has a different meaning...)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>