5 ms·
The common-sense approach would be not to introduce such defaults. def foo(bazzes=None): _baz = bazzes or [] ...
by avip 7y ago
The common-sense approach would be not to introduce such defaults.
def foo(bazzes=None):
_baz = bazzes or []
...
- dnautics 7y agoThen why doesn't the language prohibit having a default of anything mutable?
- stefco_ 7y agoPython is generally terrible at providing immutable types and workflows. No such thing as a constant, class variables are mutable by default, no built-in immutable dictionary class, etc. I use a linter to catch this sort of thing and subclass `collections.namedtuple(...)` whenever I need to at least try to abolish mutability. It's one of the worst things about the language. [edit] You can argue that there would be use cases for mutable defaults, and as with any edge use case you'd be right in asserting its existence. Unfortunately, I can't think of any solution (typing, changing function argument evaluation rules, etc) that wouldn't fundamentally change the language and break just about every sizable python library in existence. This looseness is baked deep into the language as far as I can see.
- yedpodtrzitko 7y ago- how does the language know a thing is (not) mutable? - how does it know you're not doing that on purpose?
- dnautics 7y ago1) aren't there specific immutable pass-by-value forms in python? If you pass a default integer, for example, and change the value of that variable in the function body, the next call will respect the default parameter and not the mutated parameter. 2) good point.
- fiddlerwoaroof 7y agoThe mutable default is sometimes useful as a quick way to memoize a function
- bjoli 7y agoI would argue that that is an edge case that should be done with decorators. The whole mutable default thing bites everyone at least once, and at best it just means more code to do the same thing.
- stefco_ 7y agoThis is the idiomatic way to add mutable defaults.