Python naming conventions for functions that modify an object or return a modified copy

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

Suppose you want to implement both options, what should you name functions?

Example. Suppose you want to use a function crop()for an Image object. I Ruby it was simple because you should use crop()if you return a copy and crop!()if you change the original instance.

+5
source share
4 answers

, PEP , , , / python, . , :

>>> 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']

crop() [ ] cropped() [ ].

EDIT: ruby, python ( / , ).

!

+5

, list.sort() list.reverse(), list sorted() reversed(), - (reversed() ). , , , .

NumPy out, , , . out .

+2

AFAIK " Python" . , , , , : , copy kwarg, , , True.

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

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

smth.crop()

And if I want to return the changed object, I would use the function:

crop(smth)

This way you save functions in a functional style (without side effects) and methods in OOP style (with side effects).

However, I also want to Python allowed symbols !and ?names of functions, such as Ruby and Lisp.

0
source

All Articles