[SciPy-dev] Best ways to set default values consistent within a module
David Cournapeau
david at ar.media.kyoto-u.ac.jp
Sun Jun 10 04:05:11 EDT 2007
Francesc Altet wrote:
> El ds 09 de 06 del 2007 a les 19:46 +0900, en/na David Cournapeau va
> escriure:
>> Hi,
>>
>> I have a question concerning default values for scipy functions.
>> Basically, I have a class which have a significant number of function,
>> several private, several private, and they provide different levels of
>> the same functionality, with similar arguments with default values.
>>
>> class foo:
>> def foo1(level = def1, dim = def2):
>> pass
>> def foo2(level = def1, dim = def2):
>> pass
>>
>> What is the best way to maintain the default values consistent ? What I
>> do for now is to set the default values from global variables; another
>> way is to use the syntax *args, **kw, but I don't really like it myself,
>> because then you do not know what the values when doing help foo.foo1 (I
>> found this really annoying in matplotlib docstrings, for example).
>
> Well, if you can afford requiring Python 2.4 or higher in your
> application, one possibility is to use decorators. For example,
> consider this:
>
> ------------------------- prova.py ---------------------------------
> def add_dflts():
> def decorator(func):
> def wrapper(hello, k=1, level="lvl1", dim=3):
> return func(hello, k, level, dim)
> wrapper.__name__ = func.__name__
> wrapper.__dict__ = func.__dict__
> wrapper.__doc__ = func.__doc__
> return wrapper
> return decorator
>
> @add_dflts()
> def test(hello, k, level, dim):
> "Hello test"
> print hello, k, level, dim
>
> test("Hello!", k=2)
> ---------------------------------------------------------------------
>
> Importing this on ipython gives:
>
> In [1]:import prova
> Hello! 2 lvl1 3
>
> So, the decorated test() function honors the defaults stated in the
> decorator. Also, you can see how the doc string is conveniently updated
> as well:
>
> In [2]:prova.test?
> Type: function
> Base Class: <type 'function'>
> String Form: <function test at 0xb76a341c>
> Namespace: Interactive
> File: /tmp/prova.py
> Definition: prova.test(hello, k=1, level='lvl1', dim=3)
> Docstring:
> Hello test
Mm. how is this different than "classic" function factory ? Depending on
2.4 features is a no-no anyway, because this code is meant to be used in
scipy. Well, I will think about using function generators, but this
sounds a bit overkill for what I want to do.
>
> As Phillip Eby says in www.ddj.com/184406073 (a strongly recommended
> read):
>
Argh, it made me realize that I was using some python2.4 specific
features in my code already :)
cheers,
David
More information about the SciPy-Dev
mailing list