5

I was wondering if there is a proper Python convention to distinguish between functions that either alter their arguments in place or functions that leave their arguments in tact and return an altered copy. For example, consider two functions that apply some permutation. Function f takes a list as an argument and shuffles the elements around, while function g takes a list, copies it, applies f and then returns the altered copy.

For the above example, I figured that f could be called permute(x), while g could be permutation(x), using verbs and nouns to distinguish. This is not always really optimal, though, and in some cases it might lead to confusion as to whether an argument is going to get changed along the way - especially if f were to have some other value to return.

Is there a standard way to deal with this problem?

1 Answer 1

7

There is no handy naming convention, not written down in places like PEP-8 at any rate.

The Python standard library does use such a convention to a certain extend. Compare:

listobj.sort() listobj.reverse() 

with

sorted_listobj = sorted(listobj) reversed_iterator = reversed(listobj) 

Using a verb when acting on the object directly, an adjective when returning a new.

The convention isn't consistent. When enumerating an iterable, you use enumerate(), not enumerated(). filter() doesn't alter the input sequence in place. round() doesn't touch the input number object. compile() produces a new bytecode object. Etc. But none of those operations have in-place equivalents in the Python standard library anyway, and I am not aware of any use of adjectives where the input is altered in-place.

Sign up to request clarification or add additional context in comments.

4 Comments

list.reverse and reversed as well.
Yeah, sorting came to mind, but this does require an object-based approach, which is not always applicable.. By the way, sorted is an adjective, not a noun ;-)
@Joost: shrug, foreign grammar, I am a software engineer, not a linguist. :-P (but yeah, corrected). It doesn't really matter that listobj.sort() is a method here; the same would apply to sort(listobj) vs. sorted(listobj).
Ah, you're right. That works quite nicely, actually. My example would become permute(x) vs permuted(x), which is quite clear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.