optional arguments

Andrew Dalke dalke at dalkescientific.com
Mon Sep 17 05:46:00 EDT 2001


Silvio Arcangeli wrote:
>I have to call two different functions when the object is instantied like
>c=Connection()
>and when it is instantiated like
>c=Connection(def_ip, 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 several ways:

1) use default arguments that a caller wouldn't pass in, like

class Connection:
  def __init__(self, ip=None, port=None):
    if ip is None and port is None:
      .. no arguments passed in
    else:

I do this a lot.

2) sometime None is a possible input, so you can make things
more obscure with

_unassigned = []
class Connection:
  def __init__(self, ip=_unassigned, port=_unassigned):
    if ip is _unassigned and port is _unassigned:
      .. no arguments passed in
    else:
      ...

I've never seen this used in real code.  You probably
shouldn't use this.

3) if you really want to check the number of arguments

class Connection:
  def __init__(self, *args):
    if len(args) == 0:
        .. no arguments passed in
    else:
        ...

4) If you also want to allow kwargs

class Connection:
  def __init__(self, *args, **kwargs):
    if len(args) + len(kwargs) == 0:
      .. no arguments passed in
    else:
      ..

In newer Pythons, suppose you have Conn0 for the 0 arg
case and Conn2 for the 2 arg case.  Then this works.

def Connection(*args, **kwargs):
    if len(args) + len(kwargs) == 0:
      return Conn0()
    else:
      return Conn2(*args, **kwargs)

(In older Pythons, the last line would be
      retun apply(Conn2, args, kwargs)


Rather, it should work.  I haven't tested it.  :)

                    Andrew
                    dalke at dalkescientific.com







More information about the Python-list mailing list