Returning 'None' on Instantiation ?

Alex Martelli aleaxit at yahoo.com
Fri Jun 1 12:23:09 EDT 2001


"Dave Haynes" <Dave.Haynes at sia-mce.co.uk> wrote in message
news:c396ce35.0106010528.46f144db at posting.google.com...
> Is there a way to optionally return 'None' on instantiation? I'm

Sure!  Just make sure that what you call for instantiation
is a FUNCTION and you can return whatever you like.  This
design pattern is called "factory functions".

> thinking of something like the following:
>
> class myClass:
>     def __init__(self, param):
>
>         if <check param>:
>             <initialise data members>
>         else:
>             <make self a 'None object'>

Refactor to:
class myClass:
    def __init(self, param):
        <initialize data members>
_myClass = myClass
def myClass(param):
    if <check param>:
        return _myClass(param)
    else:
        return None

The Pythonic twist on this is that we let the factory
function's name re-bind the class's name, so from the
point of view of any caller it's transparent that we
ARE using a factory-function.  This is not strictly
necessary and in fact it could be clearer to have
different names, but it's one possibility.

> myParam = GetParam()
> myObj = myClass(myParam)
>
> if myObj:
>     print 'Okay'
> else:
>     print 'Couldn't make myObj from myParam'

This caller-code works exactly as you desire when
you use factory-function.

>  This is a fairly common state of affairs.

Sure, that is why Factory is such a crucial design
pattern -- the start of them all, in fact.

> If there's nothing specific
> in Python to accomodate this, what methods are considered robust by
> this NG?

Factory is perfectly-robust.  The only Python specific
part is the possibility to "reuse the names", but it's
debatable whether that adds anything to actual use, and
it sure doesn't add anything to _robustness_:-).


Alex






More information about the Python-list mailing list