Namespaces are one honking great idea

Chris Angelico rosuav at gmail.com
Mon Jul 4 22:58:19 EDT 2016


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?

# demo.py
pi = 3.14
def stupidfib(x):
    if x < 2: return x
    return stupidfib(x-1) + stupidfib(x-2)


Namespace asdf: # (or class, however it's done)
    def foo(x):
        return stupidfib(x * pi) / pi

How should foo reference those "even more global" names? "from .
import pi, stupidfib" would work if you converted the module into a
package ("mv demo.py demo/__init__.py"), and "from demo import pi,
stupidfib" would work if you converted the namespace into a peer
module. Either could make sense.

ChrisA



More information about the Python-list mailing list