Passing dictionary as an optional argument?

248 views
Skip to first unread message

Georgi Guninski

unread,
Jun 15, 2023, 1:28:25 AM6/15/23
to sage-...@googlegroups.com
I am not python expert, but got hurt by passing dictionary as
optional argument.

Session:

In [1]: def f(n,a,ca={}):
...: for i in range(n):
...: ca[i+a]=i+a
...: print(i,"len(cac)",len(ca))
...:

In [2]: f(2,2)
0 len(cac) 1
1 len(cac) 2

In [3]: f(2,4)
0 len(cac) 3
1 len(cac) 4

What is the scientific way to avoid `0 len(cac) 3`?

Nico Van Cleemput

unread,
Jun 15, 2023, 1:34:04 AM6/15/23
to sage-...@googlegroups.com
Hi George

The reason is that you are using a mutable object as a default object, but it is only instantiated once and then reused. See e.g. here for a longer explanation: https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422

To briefly give the solution: use ca=None and then create the dictionary in your function if ca is None.

Cheers
Nico

Op do 15 jun 2023 om 07:28 schreef Georgi Guninski <ggun...@gmail.com>:
--
You received this message because you are subscribed to the Google Groups "sage-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sage-devel+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sage-devel/CAGUWgD_DgiifZDyxJWLNPEm0vsWNfpn_xj0UJjn9B9QiQOBZLw%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages