[Python-ideas] Improve error message when missing 'self' in method definition

Steven D'Aprano steve at pearwood.info
Wed Oct 5 19:34:48 EDT 2016


On Wed, Oct 05, 2016 at 09:02:50PM +0200, Ivan Levkivskyi wrote:

> I agree with Yury here. There are corner cases (like what to do with
> classmethods etc). If behaviour for all of them are specified, it would be
> quite straightforward to implement this.

I don't know... there's a lot of corner cases and I don't think we can 
improve them all.

Here's the suggested exception from PyPy:

    TypeError: f() takes exactly 1 argument (2 given). Did you forget 
    'self' in the function definition?


What happens if f() takes a mix of positional and keyword arguments? 
What if it takes arbitrary positional arguments?

There are also classmethods, staticmethods, and any arbitrary 
descriptor. And don't forget ordinary functions too. How will this 
affect them?

Before accepting this patch, I think that we need to ensure that it 
improves at least *some* cases (not necessarily all) while it does not 
make any of the remaining cases worse.

I wonder whether an alternate approach might be better. Instead of 
trying to guess whether the method signature is wrong when the method is 
called, maybe the default metaclass (type) could introspect the 
namespace, inspect each callable in the namespace, and raise a 
warning (not an error) if the first argument is not `self` (for 
regular methods) or `cls` (for classmethods). It's not that self is 
mandatory, but it's conventional, and if we're going to guess that the 
name ought to be `self` at method call time, maybe we should guess that 
the name should be `self` when we build the class.



-- 
Steve


More information about the Python-ideas mailing list