Can I use the built-in name as the method name of a Python class?

I have a class that does 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): self.set(value) def set(self, value): self.value=value def add(self, value): self.value += value def sub(self, value): self.value -= value 

The problem is the set method, but defining it as a class method should not contradict the set () built-in function.

The Python style guide argues that function and method argument names should not shade built-in functions, but is this the case for method names?

Obviously, I could choose a different method name, but the question is more general and valid for other possible method names (e.g. filter, sum, input).

+7
source share
3 answers

All you need to not create shadow embedded names is that you do not want to stop yourself from using 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 built-in set so that there are no conflicts, the only problem is that if you want to use set inside the class definition

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

Inside the class definition - and only there - the built-in name is obscured, so you should consider which option you would prefer: an unlikely scenario where you need to use set to define a class scope variable and get an error or use an unintuitive name for your method.

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

+4
source

Are you okay. You simply do not want to overwrite the built-in modules if they are the built-in __init__ __iter__ method, etc. If you do not implement the functionality expected by these methods.

You “overwrite” an inline function as a class method, which means that you are not overwriting anything. It is acceptable.

+1
source

Namespaces - one great idea - the same thing in this case, the name set defined, but it only exists in the namespace bounded by the Entry class and does not interfere with the built-in function name.

+1
source

All Articles