Checking parameters prior to object initialisation

B

Brett_McS

Fairly new to Python (and loving it!)

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?


Cheers,
Brett McSweeney
 
P

Peter Otten

Brett_McS said:
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"

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
 
B

Bruno Desthuilliers

Brett_McS a écrit :
Fairly new to Python (and loving it!)

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 don't think so.
or is
there some other, preferred, method?

If you really have to check, do it in the object's initializer (the
__init__ method), and raise an exception if necessary.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top