Namespaces are one honking great idea

Steven D'Aprano steve at pearwood.info
Mon Jul 4 23:35:14 EDT 2016


On Tue, 5 Jul 2016 12:58 pm, Chris Angelico wrote:

> On Tue, Jul 5, 2016 at 12:34 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> *** IF *** you are willing to push the code out into its own separate .py
>> file, you can use a module and write your code in a more natural form:
>>
>>
>> # module example.py
>> var = 999
>>
>> def spam(arg):
>>     return eggs(arg) + var
>>
>> def eggs(arg):
>>     return arg*2
>>
>>
>> What I'm calling a "namespace" is just a module object that lives inside
>> another module, without requiring a separate .py file. It only uses
>> the "class" statement for pragmatic reasons: there's no other statement
>> available that will do the job.
> 
> If you push your code into a separate .py file, you can reference the
> original module by importing it. Is that also the normal way to use
> "outer" functions etc from inside a namespace?

Good question! 

With the current implementation, importing should work, but it's not
necessary. The surrounding module (the real .py module) is inserted into
the name resolution path of functions:

py> x = 999
py> @namespace.Namespace
... class Test:
...     def test():
...             print(x)
...
py> Test.test()
999


Of course, the module-global x will be shadowed by any x in the Test
namespace (which is the intent), and you cannot assign to them (also a
feature). A bare `x = 1` inside the function will make x a local, unless
you declare it global first, in which case it should assign to the Test
namespace scope instead.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list