Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 through2) 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.

like image 247
Ignat Insarov Avatar asked Aug 16 '26 11:08

Ignat Insarov


1 Answers

Python has importing built in to the language at a more basic level than Javascript does, almost all use cases are covered by a simple import statement.

For your example, all it really boils down to is:

from module import exports as x

So, there's not need to look for code savings by changing module.

The other part of the question is how, as a module author, would you restrict people to seeing only a single symbol.

Generally this is not required except to help users know what are public functions vs implementation details. Python has a few common idioms for this:

  • Any names that start with a leading underscore, such as _helper, are considered private. They can be accessed as normal, but the implication is you should not.
  • If a module level variable __all__ = [...] exists, only the strings it contains are considered public. The names must seperatedly be declared in the module.

As well as being documentation, both of these do affect one aspect of the module import:

from module import *

Using a star import is generally discouraged, but only public names will be brought in to the local namespace.

like image 147
gz. Avatar answered Aug 19 '26 02:08

gz.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!