Namespaces are one honking great idea

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Fri Jul 1 22:55:13 EDT 2016


On Saturday, July 2, 2016 at 1:50:56 PM UTC+12, Kevin Conway wrote:
> Regardless, all use cases you've listed are already satisfied by use of the
> static and class method decorators.

Except for the need to decorate every such function inside the class. How about:

    import types

    def namespace(inclass) :
        "decorator which turns a class into a module."
        outclass = types.ModuleType \
          (
            name = inclass.__name__,
            doc = inclass.__doc__,
          )
        for attr in dir(inclass) :
            if not attr.startswith("__") or attr in ("__package__",) :
                setattr(outclass, attr, getattr(inclass, attr))
            #end if
        #end for
        return \
            outclass
    #end namespace

Example use:

    @namespace
    class try_it :
        "try it!"

        val = "some text"

        def func() :
            print("func got called")
        #end func

    #end try_it



More information about the Python-list mailing list