[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

more pythonic way

-----Mensaje original-----
De: Python-list [mailto:python-list-bounces+felix=epepm.cupet.cu at python.org]
En nombre de Grant Edwards
Enviado el: lunes, 11 de febrero de 2019 02:46 p.m.
Para: python-list at python.org
Asunto: Re: more pythonic way

On 2019-02-11, Felix Lazaro Carbonell <felix at epepm.cupet.cu> wrote:

> Could you please tell me wich way of writing this method is more pythonic:
>     def find_monthly_expenses(month=None, year=None):
>         month = month or datetime.date.today()
> Or it should better be:
>         if not month:
>             month = datetime.date.today()

>The most pythonic way is to do this:
>   def find_monthly_expenses(month=datetime.date.today().month,
>      ...
>And then start a month-long argument on the mailing list about how the
behavior of parameter default values is wrong and needs be changed.
>Grant Edwards               grant.b.edwards        Yow! I always have fun
>                                  at               because I'm out of my
>                              gmail.com            mind!!!

Thanks Grant:

 but now I think I should have mentioned that this is a method in a Django
model, and default arguments are evaluated once when the method is defined,
not each time the method is called.
So, your way, wil yield the date when Django was started and not the date in
wich this method is called, and the date I intend to get is the one when the
method is called. I think that I shouldn't call datetime.date.today() as a
default value for the method's parameters.