cannatag cannatag - 1 year ago 129
Python Question

Can I use a builtin name as a method name of a Python class?

I have a class that performs some simple data manipulation, I need three methods: set, add, sub:

class Entry(): # over-simplified but should be enough for the question
def __init__(self, value):
def set(self, value):
def add(self, value):
self.value += value
def sub(self, value):
self.value -= value

The problem is with the "set" method but defining it as a class method should not clash with the "set()" builtin function.

The Python Style Guide states that argument names of functions and methods should not shadow built-in functions, but it's this the case for method names?

Obviously I could choose another method name, but the question is more generic and valid for other possible method names (i.e. filter, sum, input).

Answer Source

The whole thing about not shadowing builtin names is that you don't want to stop your self from being able to use them, so when your code does this:

x.set(a) #set the value to a
b = set((1,2,3)) #create a set

you can still access the builtin set so there is no conflict, the only problem is if you wanted to use set inside the class definition

class Entry():
    def __init__(self, value):
    def set(self, value):
    possible_values = set((1,2,3,4,5)) #TypeError: set() missing 1 required positional argument: 'value'

Inside the class definition - and there only - is the built in name shadowed, so you have to consider which you would rather settle for: the unlikely scenario where you try to use set inside the class definition and get an error or using a non-intuitive name for your method.

Also note that if you like using method names that make sense to you and also want to use set in your class definition you can still access it with builtins.set for python 3 or __builtin__.set for python 2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download