[Tutor] Assigning function keywords dynamically

Tim Peters tim.one@comcast.net
Sun Jan 5 18:36:21 2003


[Charlie Clark]
> ...
> I have got a little report generator that generates reports for
> people with different frequency (daily, weekly, monthly). What I wa=
nt
> is a function  that takes the frequency and returns the correct fut=
ure
> date for the next run.
>
> current implementation using mx.DateTime
>
> from mx.DateTime import now(), DateTime.RelativeDateTime
>
> def new_date(interval):
> =09if interval =3D=3D "monatlich":
> =09=09return now() + RelativeDateTime(months=3D+1)
> =09elif interval =3D=3D "w=F6chentlich":
> =09=09return now() + RelativeDateTime(weeks=3D+1)
> =09elif interval =3D=3D "t=E4glich":
> =09=09return now() + RelativeDateTime(days=3D+1)
> =09else:
> =09=09return "Invalid interval"
>
> While this is fine it seems a little verbose and clumsy and not qui=
te
> Python. What would be a better way of doing this?

You're building a mapping from strings to durations, which screams "d=
ict".
Like so:

_name2dur =3D {"monatlich": RelativeDateTime(months=3D+1),
             "w=F6chentlich": RelativeDateTime(weeks=3D+1).
             "t=E4glich": RelativeDateTime(days=3D+1),
            }

def new_date(interval):
    dur =3D _name2dur.get(interval)
    if dur is None:
        raise ValueError("unknown interval '%s'" % interval)
    return now() + dur

> Also would it be a good idea to raise an exception in the else
> statement?

Probably.  The caller presumably expects to get some kind of date obj=
ect
back from this, not some kind of string, so when it does return a str=
ing it
will probably raise some kind of baffling exception later (like "can'=
t add
time to string"), or perhaps "Invalid interval" will get stored away
somewhere and printed 3 months later.  It would be hard to guess what=
 went
wrong then.  As a general rule, it's thoroughly appropriate for a fun=
ction
to raise an exception when a caller asks it to do something silly, an=
d
you're doing the caller a favor by not letting it get away with that =
when it
does.