I want to write a method like this:
def method(self, long_api_parameter_name=None):
if long_api_parameter_name is None:
long_api_parameter_name = self.DEFAULT_X
return self.another_method(long_api_parameter_name)
However I have been advised not to reassign to a method parameter. Is there any [semi]official recommendation or at least a consensus within the community?
I would probably write it as
long_api_parameter_name = long_api_parameter_name or self.DEFAULT_X
for brevity, but yes, it's a pretty common pattern in Python.
Update:
If the passed value might evaluate as false, you have to do something slightly more complex:
NOT_PASSED = object()
def method(self, long_api_parameter_name=NOT_PASSED):
long_api_parameter_name = long_api_parameter_name if long_api_parameter_name is not NOT_PASSED else self.DEFAULT_X
This will allow false values - even None to be explicitly passed, but fall back to the default if nothing is specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With