optional arguments
Martin von Loewis
loewis at informatik.hu-berlin.de
Mon Sep 17 05:52:12 EDT 2001
Silvio Arcangeli <sarcangeli at montrouge.sema.slb.com> writes:
> class Connection:
> def __init__(self, ip=def_ip, port=def_port)
> ...
>
[...]
> how can I tell wheter no arguments were passed from the user or whether
> they were passed but they were just like the default values?
There are two options. One is, give them default values that nobody
else could ever pass, like
class NoValue:pass
_novalue = NoValue()
del NoValue
class Connection:
def __init__(self, ip=_novalue, port=_novalue):
if ip is _novalue:
ip = def_ip
# other actions to perform if ip was not given
Now, this still could be cheated, if somebody really meant
to. Therefore, most people are happy with using None as the default
value:
class Connection:
def __init__(self, ip=None, port=None):
if ip is None:
ip = def_ip
# other actions to perform if ip was not given
If you really *must* find out what arguments have been passed, use a
varargs syntax:
class Connection:
def __init__(self, *args):
try:
ip = args[0]
except IndexError:
ip = def_ip
# other actions to perform if ip was not given
BTW, if you require ip and port always to be passed together, you
might follow the convention of the socket module, i.e. an IPv4 address
is always passed as a pair (host, port):
def_addr = (def_ip, def_port)
class Connection:
def __init__(self, addr = None):
if addr:
ip, port = addr
else:
ip, port = def_addr
Regards,
Martin
More information about the Python-list
mailing list