[Tutor] Assigning function keywords dynamically

alan.gauld@bt.com alan.gauld@bt.com
Mon Jan 6 14:28:44 2003


> from mx.DateTime import now(), DateTime.RelativeDateTime
>=20
> def new_date(interval):
> 	if interval =3D=3D "monatlich":
> 		return now() + RelativeDateTime(months=3D+1)
> 	elif interval =3D=3D "w=F6chentlich":
> 		return now() + RelativeDateTime(weeks=3D+1)
> 	elif interval =3D=3D "t=E4glich":
> 		return now() + RelativeDateTime(days=3D+1)
> 	else:
> 		return "Invalid interval"

I don't know how RelativeDAteTime works but I assume it is returning=20
a fixed value. Thus I'd store them in a dictionary and do:

Intervals =3D {"mon":RelativeDateTime(months=3D+1),
             "week":RelativeDateTime(weeks=3D+1),
             "day":RelativeDateTime(days=3D+1)
            }

def new_date(interval):
    return now() + Intervals[interval]


That will raise an exception automatically if the key doesn't exist.

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/