[SciPy-dev] Best ways to set default values consistent within a module

Francesc Altet faltet@carabos....
Sat Jun 9 07:00:02 CDT 2007

El ds 09 de 06 del 2007 a les 19:46 +0900, en/na David Cournapeau va
> 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

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)
    Hello test

As Phillip Eby says in www.ddj.com/184406073  (a strongly recommended

Python decorators are a simple, highly customizable way to wrap
functions or methods, annotate them with metadata, or register them with
a framework of some kind. But, as a relatively new feature, their full
possibilities have not yet been explored, and perhaps the most exciting
uses haven't even been invented yet.

I'm myself not very used to them, but I apparently should ;)


Francesc Altet    |  Be careful about using the following code --
Carabos Coop. V.  |  I've only proven that it works, 
www.carabos.com   |  I haven't tested it. -- Donald Knuth

More information about the Scipy-dev mailing list