4

My app allows users define scheduling on objects, and they is stored as rrule. I need to list those objects and show something like "Daily, 4:30 pm". There is something available that "pretty formats" an rrule instance?

Armando Pérez Marqués
  • 5,661
  • 4
  • 28
  • 45
  • Not that I know of, but it would be easy to write. – Blender Feb 18 '12 at 04:46
  • There's a good explanation of `__repr__` and `__str__` here -> http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – synthesizerpatel Feb 18 '12 at 04:58
  • @synthesizerpatel Yes, I have read it, and it's good. But my question is more like how to do it using `__str__`, since it is intended for final users. – Armando Pérez Marqués Feb 18 '12 at 13:00
  • @Blender I could just make a formatted string of some/all of the internal attributes of the `rrule` instance, but what I'm looking for is for something more natural, so anyone can quickly see the recurrence without "parsing" those parameters. – Armando Pérez Marqués Feb 18 '12 at 13:03
  • You override the __str__ method with whatever you want the representation to be. def __str__(self): return "%d:%d" % ( hour, minute) .. etc.. – synthesizerpatel Feb 19 '12 at 05:24

1 Answers1

1

You simply have to provide a __str__ method and it will be called whenever something needs to render your object as a string.

For example, consider the following class:

class rrule:
    def __init__ (self):
        self.data = ""
    def schedule (self, str):
        self.data = str
    def __str__ (self):
        if self.data.startswith("d"):
            return "Daily, %s" % (self.data[1:])
        if self.data.startswith("m"):
            return "Monthly, %s of the month" % (self.data[1:])
        return "Unknown"

which pretty-prints itself using the __str__ method. When you run the following code against that class:

xyzzy = rrule()
print (xyzzy)
xyzzy.schedule ("m3rd")
print (xyzzy)
xyzzy.schedule ("d4:30pm")
print (xyzzy)

you see the following output:

Unknown
Monthly, 3rd of the month
Daily, 4:30pm
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953