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

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


On Wed, Sep 17, 2014 at 03:19:52PM +1000, Tennessee Leeuwenburg wrote:
> I would like to be able to use named sections to organise my code, much an
> inline submodules, bit without using classes or functions to organise them.
> I would use this if I had a group of related functions which were not
> written in an object-oriented-style, possibly due to not needing any shared
> state. Rather than break these out into a new file, I would like to just be
> able to use internal structure to declare the relationship. I've used the
> keyword 'block' to indicate the start of a named block.
> 
> For example,
> 
> block signin:
>      def handle_new_user():
>            do_it()
> 
>      def handle_existing_user():
>            do_it()


I think that this is very close to what C++ calls namespaces, and I 
think that the Zen of Python has something to say about namespaces :-)

For quite some time I've been mulling over the idea of having 
multiple namespaces within a single module, but my ideas haven't been 
advanced enough to raise here. While having dedicated syntax for it 
would be nice:

namespace stuff:
    a = 2
    def stuff(x): ...

assert stuff.a == 2


I *think* it should be possible to abuse the class statement to get the 
same effect, by use of a metaclass or possibly a class decorator:

@namespace
class stuff:
    a = 2
    def stuff(x): ...

assert isinstance(stuff, ModuleType)
assert stuff.a == 2


The hardest part, I think, is getting scoping right in the functions. 
What I would expect is that inside a namespace, scoping should go:

local
current namespace
module globals
built-ins

so that functions inside a single namespace can refer to each other 
without needing to give a fully-qualified name.

In other words, this sort of namespace is just like a module, but it 
doesn't need to be written in an external file.


-- 
Steven


More information about the Python-ideas mailing list