Python: When should we name the parameters we're passing?

  • A+
Category:Languages

I've been learning python recently and I'm a little confused to why people name their parameters when calling the function their naming the parameters to?

Take this code for starter

def my_funcation(greeting = 'Hello', name = 'Guest'):     return f'{greeting}, {name}. How are you?'   print(my_function('Yo', name = 'Adam')) 

It all looks good, but there's one part I don't get. Why do people specifiy the parameter name their assigning to? Is this like a convention or is it a rule to write good code?

Why can't we just write this..

def my_funcation(greeting = 'Hello', name = 'Guest'):     return f'{greeting}, {name}. How are you?'   print(my_function('Yo', 'Adam')) 

IMO, the second one is better, incase the parameter name ever changes.

 


Sometimes, it adds helpful context to the code.

What would you rather read:

enumerate('xyz', 120)  # err...what does that second arg do again? 

or

enumerate('xyz', start=120)  # oh yeah, the start index 

It allows you to modify or reorder the kwargs of the function, with no change required for the calling code.

Consider adding a new argument, in front:

def my_function(color='red', greeting='Hello', name='Guest'):     ... 

If you don't also modify the caller my_function('Yo', 'Adam'), you would have them filling the incorrect arguments now - and if you don't have a good test coverage, you might not even notice the bug until too late.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: