Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 731
sorin Avatar asked Nov 21 '11 12:11

sorin


People also ask

Can methods modify object Python?

Not only can they modify object state, instance methods can also access the class itself through the self. __class__ attribute.

Which is an example of a Python naming rule for a variable?

A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)


2 Answers

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!

like image 71
mac Avatar answered Sep 26 '22 23:09

mac


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.

like image 29
Michael Hoffman Avatar answered Sep 25 '22 23:09

Michael Hoffman