Thoughts on using isinstance

Gabriel Genellina gagsl-py at yahoo.com.ar
Wed Jan 24 13:05:11 EST 2007


At Wednesday 24/1/2007 14:21, abcd wrote:

> >Yes because usually you don't expect a list or dictionary but some object
> > that *acts* like a list or dictionary.  Or you even expect just some
> > aspects of the type's behavior.  For example that it is something you can
> > iterate over.
> >
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
>good point.  is there place that documents what methods/attrs I should
>check for on an object?  for example, if its a list that I expect I
>should verify the object that is passed in has a ??? function? etc.

Don't insist on checking! :)
Just try to use the object - you'll get an exception at first invalid usage.

By example, a lot of functions take a file parameter to output 
something on it. Usually the *only* method called is write(). So any 
object with a write() method (taking a single string argument) would 
be fine; StringIO are an example. Checking if the argument is an 
instance of the file type would make that impossible.
Anyway, sometimes it's ok to check in advance - but please consider 
to check the *behavior* you expect, not the exact instance type. In 
the example above, you can validate that fileobject has a write 
attribute: getattr(fileobject, "write"). But I'd only do that if I 
have a good reason (perhaps if the file is used after some lengthy 
calculation,and I want to be sure that I will be able to store the result)


-- 
Gabriel Genellina
Softlab SRL 


	

	
		
__________________________________________________ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 




More information about the Python-list mailing list