Negroup - wrote:
> My solution is:
> foo.py
> class MyStr(str):
>     def myStartsWith(self, options=[]):
>         if (type(options) != type([]) or not options):
>                 return 'Error'
>         else:
>                 for option in options:
>                         if self.startswith(option):
>                                 return self
>         return False
> 
> class MyFile(file):
>     def get_valid(self, options):
>         return [MyStr(valid).myStartsWith(options) for valid in
> self.readlines() if MyStr(valid).myStartsWith(options)]
> 

Hmm...

This seems like a lot of work. If the only use for this class is to call 
myStartsWith(), I would just make a standalone myStartsWith() function and not 
enclose it in a class. It will be less code for the definition and at point of 
call. MyFile has the same problem - it isn't really giving any return on the 
investment of creating a class, you could just have a standalone get_valid 
function.

Instead of returning 'Error' for a bad argument you should raise an exception, 
TypeError or ValueError or maybe both if you want to be really literal about 
what the exceptions mean. In fact, your current code is a good example of why 
exceptions are a good idea. The way you have it now, a caller must explicitly 
check for the string 'Error'. Your MyFile class doesn't do this and it will 
happily accept any 'valid' if options is None or not a list. Also, you can't 
distinguish between the result of MyStr('Error').myStartsWith(None) and 
MyStr('Error').myStartsWith(['E'). Raising an exception solves both these 
problems.

Oh, you might want to settle on a naming style, either camelCase or 
embedded_underscores but not both...

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to