internal circular class references

Carl Banks pavlovevidence at gmail.com
Wed Dec 10 22:19:16 EST 2008


On Dec 10, 8:18 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
> Ethan Furman wrote:
> > Greetings List!
>
> > I'm writing a wrapper to the datetime.date module to support having no
> > date.  Its intended use is to hold a date value from a dbf file, which
> > can be empty.
>
> > The class is functional at this point, but there is one thing I would
> > like to change -- datetime.date.max and datetime.date.min are class
> > attributes of datetime.date, and hold datetime.date values.  At this
> > point I have to have two lines outside the actual class definition to do
> > the same thing, e.g.:
>
> > <trimmed down class code>
> >   class NullDate(object):
> >       "adds null capable DateTime.Date constructs"
> >       __slots__ = ['_date']
> >       def __new__(cls, date='', month=0, day=0):
> >           nulldate = object.__new__(cls)
> >           nulldate._date = ""
> >           .
> >         .
> >         .
> >         return nulldate
> >       def __getattr__(self, name):
> >           if self:
> >               attribute = self._date.__getattribute__(name)
> >               return attribute
> >           else:
> >               if callable(dt.date.__dict__[name]):
> >                   return int
> >               else:
> >                   return 0
> >       def __nonzero__(self):
> >           if self._date:
> >               return True
> >           return False
> >       @classmethod
> >       def fromordinal(cls, number):
> >           if number:
> >               return cls(dt.date.fromordinal(number))
> >           else:
> >               return cls()
> >   NullDate.max = NullDate(dt.date.max)
> >   NullDate.min = NullDate(dt.date.min)
> > </trimmed down class code>
>
> > How can I move those last two lines into the class definition so that:
> >   1) they are class attributes (not instance), and
> >   2) they are NullDate type objects?
>
> > ~ethan~
>
> I resisted posting a similar question recently. After much
> consideration, I realized that the inability to reference a class inside
> its own definition must have been a deliberate design of the language.

I think mostly it's just a logistical issue.  It's reasonable for a
class's attributes to be objects of that class (the datetime.date
class is a perfect example of when it's useful).  It would be
preferrable to assign such objects inside the class scope like all
other class attributes.

Problem is, the class doesn't exist until after all the statements in
the class scope have been evaluated.


> So the short answer is you can't.
>
> The way you have done it is best--its not a hack and is good style.

Yes, it's straightforward and readable, a perfectly good workaround
for a very minor style issue.


Carl Banks



More information about the Python-list mailing list