[Python-ideas] A "within" keyword

Steven D'Aprano steve at pearwood.info
Sat Jun 9 05:03:55 EDT 2018


On Fri, Jun 08, 2018 at 02:41:54PM -0400, David Teresi wrote:

> One of the features I miss from languages such as C# is namespaces that
> work across files - it makes it a lot easier to organize code IMO.

I too have often wanted a sub-module namespace without the need to 
separate code into seperate files. Something like a package, but 
existing inside a single physical file. In pseudo-code:

a = 1
def spam():
    return a

namespace A:
    # conceptually, this is like a module within a module
    a = 100
    def spam():
        return a

# later
spam() + A.spam()
=> returns 101


If that looks similar to the class statement, except there's no need to 
create an instance, that's deliberate.



> Here's an idea I had - it might not be the best idea, just throwing this
> out there: a "within" keyword that lets you execute code inside a
> namespace. For example:
[...]

> within cool_namespace:
>     def foo():
>         print("foo run")
[...]
> within A.cool_namespace:
>     foo() # prints "foo run"

This sort of thing is similar to a old FAQ:

https://docs.python.org/3/faq/design.html#why-doesn-t-python-have-a-with-statement-for-attribute-assignments

so it isn't unambiguously clear what foo would mean: is it the current 
namespace foo, the surrounding namespace, or the module namespace?

Its not necessarily undoable: currently Python has what the "Learning 
Python" book calls the LEGB scoping rule:

L - local
E - enclosing function(s) or class
G - global (module)
B - builtins

It could be conceivable to add a rule to slot a namespace in there 
somewhere, but the scoping rules already are fairly hairy (e.g. classes 
and functions work a little differently, we have a sub-local scope for 
comprehensions) and I'd be cautious about making them hairier with 
something like your "within"/"with" statement.

The question I have is what is your motive for this? What problem does 
this solve for you?



-- 
Steve


More information about the Python-ideas mailing list