r/learnpython • u/ClickOk5811 • Oct 26 '26
Is None as a sentinel the standard fix for mutable default arguments, or are there better options?
I’m reading about mutable default arguments in Python. This function shares its list across calls:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b']My understanding is that defaults are evaluated once when def runs, so every call without items shares one list. The fix I’ve seen is:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsQuestions:
- Is this the idiomatic approach, or is there something better?
- For dataclasses, is
field(default_factory=list)the right equivalent? - Do linters catch this, and which ones do you use?
- Is there a legitimate case for keeping a shared mutable default?
If I’ve misunderstood something, please correct me.
13
Upvotes
21
u/Anxious_Signature452 Oct 26 '26
None as sentinel in this case is a common approach and widely used. Technically, you can use mutable default arguments, for example, as a shared cache, but I never seen something like that in production environment.
6
u/Uncle_DirtNap Oct 26 '26
There’s a new sentinel type, but people also do:
_no_val = Object()
def func(arg=_no_val):
if arg is _no_val:
pass
5
u/pachura3 Oct 26 '26
items: list|None, they won't catch it upon passing... but then they will complain about you potentially calling.append()onNone. PS. I use ruff, pylint and mypy.cached_property7
u/pontz Oct 26 '26
I type hint it as an iterable and default it as an empty tuple.
3
u/JaguarMammoth6231 Oct 26 '26
What is the desired behavior? It looks like the first snippet is intentionally taking advantage of the persistence of the default argument.
4
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Oct 26 '26 edited Oct 26 '26
I'd say this is generally idiomatic, yes. Another option would be to use a compatible, immutable type as the default, but which works best is situational.
Yes.
Linters may catch it (I think Ruff does), type checkers should catch it. As long as you use type annotations.
For the most part, no, though some people do use it as a hacky mechanism for caching. I've made some use of it in code golf, but would never do it in production.
2
u/TheRNGuy Oct 26 '26
Have a different variable inside function, and then assign it from return, doing side effect like that is anti-pattern.
Besides that, List already have method for this.
2
u/Adrewmc 29d ago edited 29d ago
items = items or []
That’s a bit easier to write.
2. Yes. I believe so.
3. You just your hint it correctly it should work.
4. There is a somewhat a use case for evaluating an argument once upon definition. Also consider this.
def start(argument, config = Config(*default_settings))
Even in the more likely
config = Configs()
def start(argument, config = config)
We may want to maintain that mutability. (It’s a fairly weak argument though most people think.)
In this case I might want my mutable configs to be created once, but have different setups. There is usually not a great reason to have a list be there but that’s just a by product.
2
u/jpgoldberg 29d ago
I am a bit surprised that nobody has mentioned PEP 661, which is adopted in Python 3.15 explicitly for defining sentinels.
The PEP describes cases where
Nonedoesn't work nicely as a sentinel, although it often does and people have been using it that way.Of course this requires Python 3.15, but better late than never.
2
u/aishiteruyovivi 29d ago
field(default_factory=list)is the right equivalent so long as you want that field's type to only be a list, and notlist | None, the former of which is usually the case. Ruff will catch mutable defaults with its B006 rule, and yeah, this approach is how you'd virtually always handle mutable defaults. You'd passNoneto indicate a default is to be used, and then set your default in the function body however you need:To my knowledge you shouldn't have typing issues regarding
Nonebeyond that point, most type checkers should infer thatitemscan then only be alist.1
u/ManyInterests from fridge import beer 29d ago
It just depends on what values callers are expected to supply.
None is very common, but can cause problems if it's also a value users or data may intentionally/incidentally supply. For example, if args are loaded from JSON, a literal null value may have a valid meaning as None when loaded, which is different than being absent.
Ellipses is what I usually use when `None` is a valid value. You can also make your own class and use that.
1
u/warden127 28d ago
You can always just use mutable defaults, but then only modify, store and return copies of them:
-2
u/Educational_Virus672 Oct 26 '26
i recommend using object from typing module since it helps readability and better then None
tho object cannot do
alternatively you use Any from typing module, it works regardless of what class function you use. it is generally risky since if you use a class function of smt like str in but you put int as its parameter it'll throw error