Empty list as a default param - the problem, and my suggested solution
guruyaya
guruyaya at gmail.com
Fri Aug 13 18:44:20 EDT 2021
I am fairly sure all of us know about this python quirk:
>>> def no_new_func(a=[]):
... a.append('new')
... return a
>>> no_new_func()
['new']
>>> no_new_func()
['new', 'new']
>>>
For some time I was bothered about that there's no elegant way to use empty list or dict as a default parameter. While this can be solved like this:
>>> def no_new_func(a=None):
... if a == None:
a = []
... a.append('new')
... return a
I have to say I find this solution very far from the spirit of python. Kinda ugly, and not explicit. So I've decided to try and create a new module, that will try and make, what I think, is a more beautiful and explicit:
>>> from new import NEW
>>> @NEW.parse
... def new_func(a=NEW.new([])):
... a.append('new appended')
... return a
...
>>> new_func()
['new appended']
>>> new_func()
['new appended']
I'd like to hear your thoughts on my solution and code. You can find and give your feedback in this project
https://github.com/guruyaya/new
If I see that people like this, I will upload it to pip. I'm not fully sure about the name I choose (I thought about the "new" keyword used in JAVA, not sure it applies here as well)
Thanks in advance for your feedback
Yair
More information about the Python-list
mailing list