Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent to java guava Preconditions

Tags:

python

Does python have any equivalent to java Preconditions library. e.g.

in java, you can check the parameters like this:

public void dummymethod(Cat a, Dog b) {
   Preconditions.checkNotNull(a, "a can not be null.");
   Preconditions.checkNotNull(b, "b can not be null.");
   /**
   your logic
   **/   
}

If a or b is null, Java throws Runtime Exception, How about python, what's the best practice here for python?

like image 266
Shengjie Avatar asked May 12 '13 21:05

Shengjie


1 Answers

While you can use assert to verify conditions, the best practice in Python is normally to document the behaviour of your function, and then let it fail if the preconditions are not met.

For example, if you were reading from a file, you would do something like:

def read_from_file(filename):
    f = open(filename, 'rU') # allow IOError if file doesn't exist / invalid permissions

rather than testing for failure cases first.

like image 53
sapi Avatar answered Nov 14 '22 22:11

sapi