Module-level functions and the module type

Chris Angelico rosuav at gmail.com
Sun Aug 17 12:20:06 EDT 2014


On Mon, Aug 18, 2014 at 1:59 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> But inside class methods we have a problem:
>
> class X:
>     def method():
>         a = b + c
>
> We can trivially decide on a rule that a must be a local, but how about b
> and c? Are they globals or attributes of the instance? Python decided on
> giving globals (well, actually nonlocals) priority, and requiring an
> explicit self, so we can write this:
>
>     def method(self):
>         a = self.b + len(c)
>
> instead of this:
>
>     def method():
>         locals.a = b + globals.len(globals.c)

I agree with this, and the C++ way of doing things is fraught with
peril. The only way it could even possibly work is with fully-declared
instance variables, and that's something Python's not going for :)

However, there's no particular reason not to have 'self' as a special
name. It's already pretty much reserved for that by convention, so
this would just mean that, in a module with an explicit metaclass,
'self' refers to the module object. You'd get something like this:

def method():
    a = self.b + len(c)

which, after all, isn't materially different from your third entry, in
that both of them need some kind of implicit namespace, just as your
explicit 'this' example from above does.

Since this would then also be at module level, it would be reasonable
for 'global x' to correspond to 'self.x', which is something that
would require a bit more language support. Currently, the version I
demonstrated has an extra level of namespacing, which is completely
unnecessary. It'd be nice to be able to unify all of that.

ChrisA



More information about the Python-list mailing list