Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #35649

Re: Function Parameters

References <assp.1708d5413f.92097A6A775D5147B1078E3F15430B9234A0F238@prato.activenetwerx.local>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-12-27 13:33 -0700
Subject Re: Function Parameters
Newsgroups comp.lang.python
Message-ID <mailman.1365.1356640464.29569.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Dec 27, 2012 at 1:16 PM, Joseph L. Casale
<jcasale@activenetwerx.com> wrote:
> When you use optional named arguments in a function, how do you deal with with
> the incorrect assignment when only some args are supplied?
>
> If I do something like:
>
>     def my_func(self, **kwargs):
>
> then handle the test cases with:
>
>     if not kwargs.get('some_key'):
>         raise SyntaxError
> or:
>
>     if kwargs.get('some_key') and kwargs.get('another_key'):
>         ...
>
> I loose the introspection that some IDE's provide from the doc strings.
>
> Any ideas on how to deal with this?

Don't use kwargs for this.  List out the arguments in the function
spec and give the optional ones reasonable defaults.

def my_func(self, some_key=None, another_key=None):
    if some_key and another_key:
        do_something()

If None is a meaningful value for the argument, then a good technique
is to use a unique object as the default instead.

MISSING = object()

def my_func(self, some_key=MISSING, another_key=MISSING):
    if some_key is not MISSING and another_key is not MISSING:
        do_something()

I only use kwargs myself when the set of possible arguments is dynamic
or unknown.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Function Parameters Ian Kelly <ian.g.kelly@gmail.com> - 2012-12-27 13:33 -0700

csiph-web