asincero wrote: > Would it be considered good form to begin every method or function with > a bunch of asserts checking to see if the parameters are of the correct > type (in addition to seeing if they meet other kinds of precondition > constraints)? Like: > > def foo(a, b, c, d): > assert type(a) == str > assert type(b) == str > assert type(c) == int > assert type(d) == bool > # rest of function follows
That's bad form. If you insist on doing something like this, at least use "isinstance(a, str)" instead of typeof. But even that breaks duck typing; if a is a unicode string, that'll fail when the function may work fine for unicode strings. You could, of course, test explicitly for the interface you need (e.g. if you need a to have "lower" and "rjust" methods, do assertion tests for them). But in practice you're generally better off simply using the object and getting the exception a few lines lower. Much of the power of dynamic typing comes from the duck typing concept, so you should really try to familiarize yourself with it. > This is something I miss from working with more stricter languages like > C++, where the compiler will tell you if a parameter is the wrong type. Stricter is the wrong word. Python is strictly typed. The difference here is dynamic vs. static typing. > If anything, I think it goes a long way towards the code being more > self documenting. Or is this a waste of time and not really "the > Python way"? There are 3 main things that you can do to help here: 1. Choose better names for the arguments so that it's obvious what they are. I don't advocate Hungarian naming, normally something like "url" or "shoeSize" will be strongly indicative of what kinds of values are acceptable. 2. Write docstrings. That will not only document the types but also how they're used, what gets returned, and perhaps limits on exactly what ranges of values are acceptable. 3. Write unit tests. They'll catch far more errors than static typing ever will. -- http://mail.python.org/mailman/listinfo/python-list