Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter Naming conventions for function in python

This isn't a big deal of a question but it bothers me, so I decided to ask for inspiration.

Assume a function defined like this:

def store(book=None, author=None):
    pass

When calling this function like this:

book = Book()
author = Author()
store(book=book, author=author)

do I have to fear sideeffects because of book=book and author=author? I am tending to redefine the function to

def store(thebook=None, theauthor=None):
    pass

but it seems a little verbose. Any suggestions?

like image 793
Aufwind Avatar asked Jun 05 '26 04:06

Aufwind


2 Answers

You have no side effects to fear. It's no different semantically than it would be if you had just called

store(book, author)

The values are stored in new variables inside the function's scope, subject to all the normal python scoping rules.

Keyword arguments do free you to use other, more specific variable names if you need to though. The names book and author are pretty generic, which is appropriate within a function, which should be reusable and therefore a little bit more abstract. But using more specific names might be appropriate within the calling scope. From that perspective, thebook and theauthor aren't really any different from book and author; you'd want to do something more like -- say -- local_book or borrowed_book -- or whatever would more precisely describe the book in question.

like image 67
senderle Avatar answered Jun 07 '26 19:06

senderle


First, there's no ambiguity or side-effect in saying store(book=book, author=author). The interpreter has no problem telling argument names from names in general.

Now, concerning the second part of your question, I don't think you should change the names of the function's arguments: after all, store() does perform its work from a book and an author, in the general sense.

Your local variables, however, might be more precise about what they contain. They probably don't reference any book or author, but one having specific characteristics like, say, the current book or the best-selling author.

So, if you wish to disambiguate names, I would suggest you rename your local variables instead.

like image 20
Frédéric Hamidi Avatar answered Jun 07 '26 18:06

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!