Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any consensus whether reassignment of method parameter is good or bad practice?

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?

like image 913
abukaj Avatar asked Dec 18 '25 13:12

abukaj


1 Answers

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.

like image 87
brunns Avatar answered Dec 21 '25 04:12

brunns