On Thu, 11 Dec 2008 at 09:33, Ethan Furman wrote:
Carl Banks wrote:
 On Dec 10, 5:26 pm, Ethan Furman <et...@stoneleaf.us> wrote:
 First of all, do you even need to wrap the datetime.date class?  With
 Python's duck typing ability, you could have a separate NullDate class
 to go alongside the datetime.date, and use a regular datetime.date
 object when the date is present, and NullDate when it's absent.  If
 necessary you can subclass datetime.date to add any new methods it
 would have to have.  Use a factory function to return either NullDate
 or a datetime.date depending on whether the dbf cell is empty.

 class ValidDate(datetime.date):
     def is_valid(self):
         return True

 class NullDate(object):
     # implement any necessary methods of datetime.date interface here
     def is_valid(self):
         return False

 def create_date_from_dbf_cell(dbf_cell):
     if dbf_cell.empty():
         return NullDate()
     return ValidDate(dbf_cell.value)


 If you do this, you don't have to muck around with __getattr__ or
 __new__ or snooping to datetime.date's class dict anything like that.


 Carl Banks

Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.).

Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense?

What Carl is saying is that since python uses duck typing ("if it quacks
like a duck, it is a duck"), all you need to do is make your NullDate
object quack enough like a date to handle your use cases, and then you
can freely mix dates and NullDates _without having to care which one a
given object is_ (python won't care).  (Until you do care, at which
point you can use isinstance to find out if it is a NullDate).

As far as I can see, your requirements as you've outlined them can be met
by mixing date objects and appropriately implemented NullDate objects.
And that way NullDates will _only_ represent null dates, thus making
its name more meaningful :).

To do this you just need to implement on NullDate those methods that
are going to give NullDate the behavior you need: the rich comparison
operators, __str__, __hash__, etc.  Or it might be easier to subclass
date and override some of the methods.

Unless I'm misunderstanding your requirements, of course :)

--RDM
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to