Hi folks, Coming from a language background that has a different approach to variables (*cough* Java *cough*), I'm trying to understand Python's typing conventions and how to deal with unknown variable types in my code. And as a newbie, I'm really concerned with not writing code that will make the actual Python programmer who will be maintaining my code jump out the window from frustration.
An example: I have a directory tree containing year directories (in the form YYYY, ie, "2011"), which contain month directories (in the form MM, ie, "05"), which in turn contain files. I'm writing a Python function to iterate over the tree & return a list of the file names from either the full tree (args==None) or a specified time period within that - ie, Feb. '10 to May '11 (args==startdate, enddate). I'm not sure what the most pythonic approach to dealing with the variables here would be. I have several options: - accept datetime objects and then get the year/month info from that - accept a string (and maybe check its length, add "20" if it's two digits, or reject it if it's more than 4) - accept an integer (and maybe check that it's reasonable) My first inclination would be to only accept 4-digit year and 2-digit month integers and fail the rest, but I understand the value of dealing with different input types here. My second guess would be to use isinstance() for each possibility, since different things need to happen in each case. The "pythonic" approach, as best as I can gather, would be a try/catch block and use the exception types to do the different processing. However, for example, both trying to get a year from a string and a len() of an int raise a TypeError, and in general I'm not sure how to approach this - or am I overthinking things? Finally, I'm aware that I'm really bringing up two topics here: 1) What is the best approach in this and similar cases, in terms of actual, working code that won't make the next user of this code cry? How do/should I distinguish error types in this case?, and less importantly, 2) Can anyone help me get a good handle on the philosophical issues here? I've read several discussions (both strongly against type-checking<http://www.canonical.org/%7Ekragen/isinstance/>and more lenient<http://dobesland.wordpress.com/2007/10/07/python-isinstance-considered-useful/>, as well as good general explanations<http://www.voidspace.org.uk/python/articles/duck_typing.shtml>), but some of it's over my head, a lot of it says something like "I suggest we change Python so it does X", and I'm not sure what it all means for me and my little filename-grabbing script. It's all just a bunch of quaking to me right now ... Thanks so much, Cory
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor