T
Travis Parks
I am trying to write an algorithms library in Python. Most of the
functions will accept functions as parameters. For instance, there is
a function called any:
def any(source, predicate):
for item in source:
if predicate(item):
return true;
return false;
There are some things I want to make sure of. 1) I want to make sure
that source is iterable. 2) More importantly, I want to make sure that
predicate is callable, accepting a thing, returning a bool.
This is what I have so far:
if source is None: raise ValueError("")
if not isinstanceof(source, collections.iterable): raise TypeError("")
if not callable(predicate): raise TypeError("")
The idea here is to check for issues up front. In some of the
algorithms, I will be using iterators, so bad arguments might not
result in a runtime error until long after the calls are made. For
instance, I might implement a filter method like this:
def where(source, predicate):
for item in source:
if predicate(item):
yield item
Here, an error will be delayed until the first item is pulled from the
source. Of course, I realize that functions don't really have return
types. Good thing is that virtually everything evaluates to a boolean.
I am more concerned with the number of parameters.
Finally, can I use decorators to automatically perform these checks,
instead of hogging the top of all my methods?
functions will accept functions as parameters. For instance, there is
a function called any:
def any(source, predicate):
for item in source:
if predicate(item):
return true;
return false;
There are some things I want to make sure of. 1) I want to make sure
that source is iterable. 2) More importantly, I want to make sure that
predicate is callable, accepting a thing, returning a bool.
This is what I have so far:
if source is None: raise ValueError("")
if not isinstanceof(source, collections.iterable): raise TypeError("")
if not callable(predicate): raise TypeError("")
The idea here is to check for issues up front. In some of the
algorithms, I will be using iterators, so bad arguments might not
result in a runtime error until long after the calls are made. For
instance, I might implement a filter method like this:
def where(source, predicate):
for item in source:
if predicate(item):
yield item
Here, an error will be delayed until the first item is pulled from the
source. Of course, I realize that functions don't really have return
types. Good thing is that virtually everything evaluates to a boolean.
I am more concerned with the number of parameters.
Finally, can I use decorators to automatically perform these checks,
instead of hogging the top of all my methods?