r/Python • • Jul 22 '21

Resource Do not use mutable objects as default arguments in Python

https://medium.com/geekculture/do-not-use-objects-as-default-arguments-in-python-1c940212db2e
1.3k Upvotes

218 comments sorted by

View all comments

Show parent comments

3

u/eveninghighlight Jul 22 '21

Maybe - but I feel like it's more likely to just confuse things. There are juniors on my team and i know this kind of thing can just ruin their week

You're right that the blanket "don't" statement isn't technically true, but if you know enough to know when to use this you probably know enough to ignore this kind of medium article

-3

u/jet_heller Jul 22 '21

And if you don't know enough you've now just created a blanket prohibition in your head against doing something potentially useful in the future. This is a disservice to those who are expected to grow in knowledge and ability.

4

u/eveninghighlight Jul 22 '21

I hadn't considered that, but equally I feel like there's always a process of unlearning as we get better at stuff

I still feel like the potential is for more harm than good for a junior reading this, unless the author explicitly recommends against it

8

u/Ph0X Jul 22 '21

Saying "potentially useful" implies that there's no other way of doing it. The alternative maybe requires a few lines of infrastructure, but is orders of magnitude more readable and will save you and others a ton of headache in the future.

Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.

Notice the order, it matters. Explicit is better than implicit. Yes simple is better than complex, but complex is better than complicated, and your solution is indeed complicated because it relies on hacky side-effect that is very hard to notice.

1

u/antiproton Jul 22 '21

There are always better ways to do something like this. You don't give people who are learning a bunch of weird 'semi-rules' to store in their head on the off chance they'll encounter some corner case that would be conveniently resolved with this knowledge.

One of the fundamental precepts of python is to avoid doing things that behave in unexpected or unintuitive ways. This is absolutely one of those cases. Arguing against it "just in case" feels contrarian for the hell of it.

1

u/jet_heller Jul 22 '21

Arguing you simply must never do what the language maintainers have purposely left in is beyond contrarian.