[Tutor] A class that instantiates conditionally ?

Steven D'Aprano steve at pearwood.info
Thu Mar 3 15:02:23 CET 2011


David wrote:

>>> class MyClass_2(object):
>>>    def __new__(self, condition):
>>>         if condition:
>>>               return object.__new__(self)
>>>         else:
>>>               return None

[...]
> Spot on. It would require two "if" tests, one inside __new__() and
> another in the code.

You will always need at least two if tests: once in the function 
producing the result ("does the test succeed? if not, return this 
instead...") and once in the code using the result ("did the magic value 
get returned?").

Consider str.find()... the caller has to check whether it returns -1, 
but the find method itself has to check whether the search string is 
found or not, and return -1 if it is not. This may or may not require a 
*literal* if statement, but there's still an implied test in the code.


> I found your mention of try/except there especially helpful, because
> it was a pertinent reminder that I was not thinking in "ask forgiveness
> not permission" mode. This (newbie mistake) occurred because I
> wanted my application to continue, not abort with an exception, but
> after your prompt I recalled that "except" doesn't have to raise exceptions
> it can do other things.

Fair enough, and arguably having the class raise an exception is a 
better design, but with all the people saying your original design was 
"too clever", I'd like to give it some love :) I think the design is 
just clever enough. I would consider using it if I were designing 
something like the regular expression match and search methods, which 
return None if the regex doesn't match.



-- 
Steven


More information about the Tutor mailing list