Question

What would be the naming conventions in Python for functions that can return a modified object or that just modifies the instance.

Let's assume you want to implement both, how you should name the functions?

Example: Let's assume that you want a crop() function for an Image object. I Ruby it was simple because you should use crop() if you return a copy and crop!() if you modify the original instance.

Was it helpful?

Solution

Not sure if there is a precise guideline in some PEP, but looking at how certain functions/method work in python core I personally use verb conjugation. For example, inspired by:

>>> l = list('hello world')
>>> l
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> sorted(l)
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> l
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> l.sort()
>>> l
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

I would name your functions crop() [modify object in place] and cropped() [return a modified copy].

EDIT: I don't know ruby, but in python the distinction between the two is purely conventional (function / method behaviour is independent from how you call it).

HTH!

OTHER TIPS

In the standard library, there are methods like list.sort() and list.reverse() which modify the list in place, and functions like sorted() and reversed() which return something new (reversed() returns an iterator rather than a new list). But if it makes more sense to have an instance method than a function, I wouldn't do this just to keep this convention.

In NumPy, many functions and methods have an out keyword argument that allow you to specify that the output should go to an existing array rather than creating a new one. You can even make the out array one of the input arrays.

There are no "Python-wide" conventions for this AFAIK. However, a project I work on has a convention that may be useful to you: if a function can modify its argument in-place, it has a copy kwarg that determines whether it operates on a copy of its input, and defaults to True.

def crop(x, copy=True):
    if copy:
        x = x.copy()
    _do_inplace_crop(x)
    return x

If I want something to be modifiable in place, I would write a method:

smth.crop()

And if I would like it to return a modified object, then I would use a function:

crop(smth)

That way you keep functions in functional style (no side effects), and methods in OOP style (with side effects).

However, I also wish Python allowed ! and ? characters in function names like Ruby and Lisp.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top