Python 3K or Python 2.9?
Alex Martelli
aleax at mac.com
Wed Sep 12 11:29:55 EDT 2007
Duncan Booth <duncan.booth at invalid.invalid> wrote:
...
> As for omitting 'self' from method definitions, at first site you might
> think the compiler could just decide that any 'def' directly inside a
> class could silently insert 'self' as an additional argument. This
> doesn't work though because not everything defined in a class has to be
> an instance method: static methods don't have a self parameter at all,
> class methods traditionally use 'cls' instead of 'self' as the name of
> the first parameter and it is also possible to define a function inside
> a class block and use it as a function. e.g.
Actually you could do the "magic first-parameter insertion" just when
returning a bound or unbound method object in the function's __get__
special method, and that would cover all of the technical issues you
raise. E.g.:
> class Weird:
> def factory(arg):
> """Returns a function based on its argument"""
>
> foo = factory("foo")
> bar = factory("bar")
> del factory
>
> When factory is called, it is a simple function not a method. If it had
Sure, that's because the function object itself is called, not a bound
or unbound method object -- indeed. factory.__get__ never gets called
here.
> class C:
> def method(self): pass
>
> and
>
> def foo(self): pass
> class C: pass
> C.method = foo
>
> both of these result in effectively the same class (although the second
> one has a different name for the method in tracebacks).
And exactly the same would occur if the self argument was omitted from
the signature and magically inserted when __get__ does its job.
> That consistency really is important. Whenever I see a 'def' I know
> exactly what parameters the resulting function will take regardless of
> the context.
And this non-strictly-technical issue is the only "true" one.
> Another area to consider is what happens when I do:
>
> foo = FooClass()
>
> foo.bar(x)
> # versus
> f = foo.bar
> f(x)
>
> Both of these work in exactly the same way in Python: the self parameter
And so they would with the "__get__ does magic" rule, NP.
> My point here is that in Python the magic is clearly defined and
> overridable (so we can have static or class methods that act
> differently).
And so it would be with that rule, since staticmethod &c create
different descriptor objects.
Really, the one and only true issue is that the Python community doesn't
like "magic". It would be perfectly feasible, we just don't wanna:-).
Alex
More information about the Python-list
mailing list