Creating objects you don't actually want

anton muhin antonmuhin at rambler.ru
Tue Feb 10 06:25:38 EST 2004


Chris Lyon wrote:

> If you wish to create an object:- 
> 
> for item in os.listdir('dir'):
>     sfx = sfxobject(item)
> 
> 
> class sfxobject(object):
>     def __init__(self, filename):
>         if isfile(filename):
>             self.filename = filename
>             # all kinds of other parameter setting
> 
> If the creation fails for any reason you are left with an object which
> is not really a 'proper' object how is it best to deal with this
> circumstance?
> 
> Do you raise an exception and perform the creation line within a try:
> except: and then delete it?
> 
> 
> class sfxobject(object):
>     def __init__(self,filename):
>         if isfile(filename):
>             self.filename = filename
>             # all kinds of other parameter setting
>          else:
>             raise sfxobjectError
> 
> for item in os.listdir('dir'):
>     try:
>         sfx = sfxobject(item)
>     except: sfxobjectError
>         del sfx
You shouldn't delete sfx --- it won't exist.

> 
> or should you heavily check the parameter before you try to create the
> object?
> 
> for item in os.listdir('dir'):
>     if os.isfile(item):  
>         sfx = sfxobject(item)
> 
> I would think that this second method should really have all the
> checking within the object it's self but then of course you have to
> create the object to allow you to do the checks and you will still be
> left with an inapproriate object to clean up afterwards?
> 
> No doubt there are many other ways of addressing this but it's a
> problem I would love to have a deffinative answer to, unless of course
> there isn't one.

It depends on design, in some cases you would check parameters, in some 
just pass them. I generally prefer to pass parameters and catch 
exceptions if something goes wrong.

anton.



More information about the Python-list mailing list