Checking parameters prior to object initialisation

Peter Otten __peter__ at web.de
Thu May 24 06:03:30 EDT 2007


Brett_McS wrote:

> In C++ (gack!) I got used to creating a helper function with each class to
> check the class object initialisation parameters prior to creating the
> object.
> 
> In Python, this would be
> -----------------------------------------------
> import example
> 
> if example.ParametersOK(a, b, c, d):
>     newObj = example.Example(a, b, c, d)
> else:
>     print "Error in parameters"
> -----------------------------------------------
> 
> I presume this would still be considered good practise in Python, or is
> there some other, preferred, method?

Use exceptions to signal wrong parameters and move the parametersOk() test
into the initializer

class Example:
    def __init__(self, a, b, c, d):
        if a < 0:
            raise ValueError("Negative length not allowed")
        #...

Write a factory if 
- creating the Example instance carries too much overhead and wrong
  parameters are likely, or
- the checks are costly and you often get parameters known to be OK.

def make_example(a, b, c, d):
    if a < 0:
        raise ValueError("Negative length not allowed")
    #...
    return Example(a, b, c, d)

Example object creation then becomes

try:
    newObj = example.Example(1,2,3,4) # or make_example(...)
except ValueError, e:
    print e # you will get a specific message here

If the checks still have to occur in multiple places in your code you are of
course free to factor them out in a separate function.

Peter
    



More information about the Python-list mailing list