[Python-ideas] Idea: Named code blocks / inline module declarations

Steven D'Aprano steve at pearwood.info
Wed Sep 17 11:21:54 CEST 2014


On Wed, Sep 17, 2014 at 01:51:29AM -0700, Andrew Barnert wrote:
> On Sep 16, 2014, at 23:21, David Mertz <mertz at gnosis.cx> wrote:
> 
> > Why is this a misuse?
> 
> Well, for one thing, you're relying on the fact that unbound methods 
> are just plain functions, which was not true in 2.x and is still not 
> described that way in the documentation. You're also ignoring the fact 
> that the first parameter of a method should be self and the convention 
> (enforced by the interpreter 2.x, although no longer in 3.x, and by 
> various lint tools, and likely relied on by IDEs, etc.) that when 
> calling an unbound method you pass an instance of the class (or a 
> subclass) as the first argument.

While all this is true, one can work around it by declaring all your 
methods @staticmethod. But it's worse than that.

By using a class, you imply inheritance and instantiation. Neither is 
relevant to the basic "namespace" idea.

Furthermore, there's no point (in my opinion) in having this sort of 
namespace unless functions inside a namespace can refer to each other 
without caring about the name of the namespace they are in. Think of 
modules. Given a module a.py containing functions f and g, f can call g:

def f():
    return g()

without writing:

def f():
    return a.g()

Classes don't give you that, so they are not up to the job.

Modules, on the other hand, give us almost exactly what is needed here. 
We can create module instances on the fly, and populate them. A class 
decorator could accept a class and return a module instance, on the fly. 
That would still be ugly, since

@namespace
class stuff:

*looks* like a class even though it isn't, but it will do as a 
proof-of-concept.


-- 
Steven


More information about the Python-ideas mailing list