开发者

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 funct开发者_开发问答ion to

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

but it seems a little verbose. Any suggestions?


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.


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.


No, there won't be any side effects from that.

The namespace of the variables in the calling function, and the namespace of the parameters within the called function, are separate and can't affect each other.


You will not get any problem with your parameter names being the same as your variable parameters because they are not parsed the same way:

parameters: '(' [varargslist] ')'
varargslist: ((fpdef ['=' test] ',')*
          ('*' NAME [',' '**' NAME] | '**' NAME) |
          fpdef ['=' test] (',' fpdef ['=' test])* [','])

From http://docs.python.org/reference/grammar.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜