Optional Arguments
>>> def foo (arg1, arg2 = None): >>> if arg2 is None: >>> print "Argument 'arg2' was not sent"Well the example looks correct, but what happens if we do:
>>> foo ("one", None)
Argument 'arg2' was not sent
But it was! This is not the correct way of sending real optional arguments, a correct approach would be to use the varagrs:
>>> def foo (arg1, *args2):
>>> if args2 == ():
>>> print "Argument 'arg2' was not sent"
>>> if len (args2) > 1:
>>> raise TypeError ("foo() takes at most 2 arguments (%d given)" % len (args2))
We used the varargs trick to figure out how many optional positional arguments were passed to our function. We also raised an exception that matches the one sent by python.
The same thing can be performed for keyword arguments:
>>> def foo (arg1, **kwargs):
>>> if not kwargs.has_key ("arg2"):
>>> print "Argument 'arg2' was not sent"
>>> if len (kwargs) > 1:
>>> raise TypeError ("foo() takes at most 2 arguments (%d given)" % len (args2))