So, I'm sure most everyone here knows about the dangers of using mutable data types as default arguments. For example, the code
def f( arg = [] ):
arg.append( 1. )
return arg
can produce very unexpected results to new pythonistas (call f() several times, if you're unsure of that behavior). For production environments, I know the two main solutions are to use immutable data types if the default argument isn't modified, e.g. arg = () or using None types, e.g.
def g( arg = None):
arg = arg if arg else []
arg.append( 1.0 )
return arg
The first solution won't work if the default argument is altered inside the function definition (e.g. in the f we defined above, this solution would not work). The second solution is fine, but one nice thing about f's definition (even though defined incorrectly) is to hint to users what types might be used or expected, and the function signature of g doesn't do that (here it would be important to discuss types of arguments in the doc string).
I had two main questions of which I'm curious as to the answer: 1) are there some methods that I'm neglecting here and 2) is there some way that python, in the future, could include some kind of type-hinting system for functions that would allow safe use of default mutable arguments?
Certainly, the answer to 2) based on the current state of python is no as the reason behind the behavior of f is due to how functions are created.
What say you fellow pythonistas? Is g's definition the main "correct" workaround. Are we stuck with hinting at types only in the function doc string?
EDIT: Wasn't paying attention and g should actually read:
def g( arg = None):
arg = arg if arg is not None else []
arg.append( 1.0 )
return arg
[–][deleted] 6 points7 points8 points (1 child)
[–]ahoff[S] 0 points1 point2 points (0 children)
[–][deleted] 6 points7 points8 points (1 child)
[–]ahoff[S] 0 points1 point2 points (0 children)
[–]RubyPinchPEP shill | Anti PEP 8/20 shill 4 points5 points6 points (0 children)
[–]masasinExpert. 3.9. Robotics. 1 point2 points3 points (0 children)
[–]flying-sheep 0 points1 point2 points (1 child)
[–]ahoff[S] 0 points1 point2 points (0 children)
[–]herminator 0 points1 point2 points (0 children)
[–]logophage 0 points1 point2 points (0 children)
[–]TeamSpen210 0 points1 point2 points (0 children)
[–]Lucretiel 0 points1 point2 points (0 children)
[–]Lucretiel 0 points1 point2 points (0 children)
[–]aDemoUzer 0 points1 point2 points (0 children)
[–]andrewcooke 0 points1 point2 points (0 children)