Sunday, 14 May 2017

In python, "export" a custom-tailored object from a module

In JavaScript, specifically in node.js setting, one can spell module.exports = 13; in module.js, then x = import ("module.js"); elsewhere and have 13 assigned to x directly.

This saves some code when a module exports a single function, and I notice a lot of widely used packages (such as trough2) make use of it.

Is there a way to do the same in Python? With some black magic, maybe?

I do have heard of a thing called loader that's, I guess, supposed to do some manipulations with a module before making it available. In particular, I think SaltStack makes use of something like that in salt.loader, but the code is too hard for me to follow. I imagine we could write a function similar to this:

def loader(module):
    m = __import__(module)
    return m["__exports__"]

— Then define __exports__ somewhere in a module we want to import and enjoy functionality very similar to JavaScript's module.exports mechanics. But unfortunately TypeError: 'module' object has no attribute '__getitem__' prevents us from doing that.



via Kindaro

No comments:

Post a Comment