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.
Not only can they modify object state, instance methods can also access the class itself through the self. __class__ attribute.
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)
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With