I have a class called Grammar
, which holds a collection of production rules. Before doing things with a Grammar
object, I usually need to add a few extra rules to it, which should be forgotten after the current task is done. So, I'd like to add a method that returns a new Grammar
object, containing all the current object's rules as well as the new ones.
I could call this method .add
, like this:
class Grammar:
def add(self, *rules):
'''Returns new Grammar object, with 'rules' added.'''
. . .
but .add
conventionally seems to mean a method that modifies a collection by adding new elements to it.
Is there a naming convention in Python for a method that returns a new collection, with new elements "added", without giving the reader the expectation that it modifies the object?
Operator overloading?
I know that the .__add__
method is invoked by the +
operator, and there the convention is indeed that the object is not modified—like this:
working_grammar = grammar + [rule1, rule2, rule3]
I am thinking to avoid overloading an operator, in favor of a meaningful method name. However, if the overloaded operator produces conventional, expected, readable code, I'd like to know more about that—perhaps a well-known precedent in a library, or advice in a well-known style guide.