简体   繁体   中英

Naming Convention for Overloaded Parameters in Python

I was recently coding up a method in Python (numpy) that can perform its operation on either on a single element, or element-wise on an array.

For example:

def addOne(self, i):
    bigArray[i] += 1

Here i can either be a single index, or an array of them, which makes descriptively naming it difficult.

And, in the more general case, how should one name overloaded parameters that can have very different meanings? Here's a (rather contrived) example:

def doTheThing(flag, item):
    if(flag == 0):
        useOneWay(item)
    else:
        useTotallyOtherWay(item)

If item represents two totally different things here, depending on flag , how should it be named?

Would it be better to have two named parameters with defaults? eg

def doTheThing(flag, item1=None, item2=None):

Perhaps such a scenario coming up is itself an indication of bad programming practices, and the best solution is re-factoring into different methods to handle each case.

Basically, is there a Python naming convention that gives direction here? I couldn't find anything specifically referencing parameter overload in PEP8.

To try and keep this on-topic and un-opinionated, please reference some reputable source in your answer (either PEP8 or some other big name in Python). I'd be happy to hear personal opinions in the comments however.

There are several things you could do. The first thing is naming your variable accordingly:

def addOne(self, i_or_is):
    if not isinstance(i_or_is, list):
        i_or_is = [i_or_is]
    ...

But in this case, the better solution would probably be to take *args :

def addOne(self, *list_of_is):
    ...

which could be called like add(1) , add(1, 2, 3) or even add(*list_) (the last example unpacks an existing list into *args ).

If you have an argument that can mean different things, you can indeed split those into 2 arguments and only accept one. The standard library does this in the logging module :

stream - Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, a ValueError is raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM