Elektrine lite

← Feed

@grant_h@mastodon.social

Post #2075104

2026-05-02 09:25 UTC

#Python community question. What motivated the generally wise and insightful devs to make mutable parameters hold the history of every call? Given: class h(): def __init__(self,x,y=[]): self.instanceY = y self.instanceY.append(x) def __repr__(self): return(f"{self.instanceY}") h1 = h(1) print(f"{h1=}") h2 = h(2) print(f"{h1=}, {h2=}") Who would expect this: h1=[1] h1=[1, 2], h2=[1, 2] I get *how* it happens, with __defaults__. But *why*

Replies (4)

  • @brass75@twit.social 2026-05-02 11:46

    @grant_h@mastodon.social @qoyyuum@fosstodon.org because that's how mutable variables work. It seems more like you want to know why an exception wasn't made for the case where a mutable value was used as the default for a parameter.

    Open ##2476221

  • @stylus@social.afront.org 2026-05-02 12:06

    @grant_h@mastodon.social @brass75@twit.social function default arguments are evaluated when the function definition is encountered, not each time it's called. https://peps.python.org/pep-0671/ seeks to add an alternative behavior but doesn't dive into the history of how we got here

    Open ##2476224

  • @grant_h@mastodon.social 2026-05-02 13:44

    @hugovk@mastodon.social @brass75@twit.social @stylus@social.afront.org Triggered by this post: https://mastodon.social/@grant_h/116504261915412452 Parts of the thread were 'followers only' The essence: tylus@social.afront.org @grant_h@mastodon.social @brass75 function default arguments are evaluated when the function definition is encountered, not each time it's called. https:// peps.python.org/pep-0671/ seeks to add an alternative behavior ... We were wondering how to get some support for PEP 671, since it seems to give a neat way of avoiding a common footgun?

    Open ##2476225

  • @MrBerard@mastodon.acm.org 2026-05-02 13:58

    @grant_h@mastodon.social Don't think it's a mutability problem, more the fact that lists are passed by reference? (And they're mutable, but that's not really their fault)

    Open ##2476227