[Tutor] question about *args and functions
Kent Johnson
kent37 at tds.net
Fri Jan 26 16:40:46 CET 2007
shawn bright wrote:
> lo there all,
>
> if i have a function that sometimes needs a value passed to it and
> sometimes not, is this where i use *args ?
No, use an optional argument.
>
> like this
>
> def some_function(req_var, req_var2, un_req_var):
> do some stuff
> return value
>
> how would i use this if sometimes i need to process un_req_var and
> sometimes not ?
def some_function(req_var, req_var2, un_req_var=None):
do some stuff
return value
Now the caller can write some_function(1, 2) or some_function(1, 2, 3).
You can distinguish the two by checking for 'un_req_var is None'.
If None is a legitimate value for un_req_var then you need to pick some
other sentinal value. If there is no built-in value that works, create
your own:
missing = object()
def some_function(req_var, req_var2, un_req_var=missing):
Kent
More information about the Tutor
mailing list