views:

36

answers:

1

I've got a method:

def do_something(year=?, month=?):
    pass

I want the year and month arguments to be optional but I want their default to equal the current year and month. I've thought about setting two variables just before the method declaration but the process this is part of can run for months. It needs to be dynamic.

Seems like it shouldn't be hard but I'm having a mental block today so how would you do it?

+8  A: 

The idiomatic approach here would be to assign None as the default value, and then reassign within the method if the values are still None:

def do_something(year=None, month=None):
    if year is None:
        year = datetime.date.today().year
    if month is None:
        month = datetime.date.today().month

    # do stuff...

You might think that you can do def do_something(year=datetime.date.today().year), but that would cache the value so that year would be the same across all calls to do_something.

To demonstrate that concept:

>>> def foo(x=time.time()): print x
...
>>> foo()
1280853111.26
>>> # wait a second at the prompt
>>> foo()
1280853111.26
Mark Rushakoff
@Mark thanks for the heads up, that is totally correct.
Yuval A
`if not year` and `if not month` is more pythonic than `is none`. Otherwise good.
Zonda333
@Zonda: Perhaps, but that would also invalidate values of zero. Zero might be a strange value for the month, but it's plausible for the year, without any more context on the OP's exact circumstance.
Mark Rushakoff