Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't think you want this, but just in case you do :)

    def encapsulate(mod):
        import types

        out = types.SimpleNamespace()

        def replace_global_scope(f):
            # via https://stackoverflow.com/a/1144561, but tweaked for py3
            return types.FunctionType(
                f.__code__,
                out.__dict__,
                f.__name__,
                f.__defaults__,
                f.__closure__,
            )

        for name in dir(mod):
            val = getattr(mod, name)
            if callable(val):
                val = replace_global_scope(val)
            setattr(out, name, val)
        return out


This is essentially just a class but worse.



You moved the for loop inside the inner function, rather than outside.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: