On 17 August 2013 13:34, Fernando Saldanha <fsald...@gmail.com> wrote: > I am new to Python, with some experience in Java, C++ and R. > > Writing in other languages I usually check the type and values of function > arguments. In the Python code examples I have seen this is rarely done. > > Questions: > > 1) Is this because it would be "unpythonic" or just because the examples are > not really production code?
Unpythonic. Python duck-types so we tend to take things as long as the seem like they work. This is really helpful if you want to provide a custom type or data object to a function (or anything really). If it looks like a duck and quacks like a duck... you can probably make a duck sandwich. > 2) If I still want to check the type of my arguments, do I > > a) use type() or is instance() to check for type? You'd want to travel down this stack, choosing the first reasonable one: • Don't check at all • Check that it can do what you need it to do, such as by calling "iter(input)" to check that it's iterable. • Check using an ABC (http://docs.python.org/3/library/abc.html) with isinstance • Check that it has the methods you need using hasattr • Check using "isinstance(...)" against a type • Check using "type(...) is" The choices higher up are better than the choices lower down. > b) use assert (I guess not), "assert" is for things that *can't* be wrong (yet still sometimes are). Don't normally assert user input, I'd say. >raise a ValueError, Sounds right. >or sys.exit()? No. You should never be throwing a SystemExit except at top-level. > (I noticed that raising a ValueError does not stop execution when I am > running the Interactive Interpreter under PTVS, which I find inconvenient, > but it does stop execution when running the code non-interactively.) -- http://mail.python.org/mailman/listinfo/python-list