Search code examples
pythonnaming-conventionscommand-query-separation

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


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.


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!