[Python-ideas] Importing public symbols and simultainiously privatizing them, is too noisy
Chris Angelico
rosuav at gmail.com
Wed Mar 16 21:53:35 EDT 2016
On Thu, Mar 17, 2016 at 12:31 PM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> This seems like something that shouldn't be done in general, so doesn't need a language fix--but if you for some specific reason need to do it all the time, just write a function for it:
>
> def _postimport(mod, names):
> g = sys._getframe(1).f_globals
> for name in names.split():
> g['_'+name] = mod[name]
>
> So:
>
> import thingy
> _postimport(thingy, 'spam eggs cheese')
> use(_spam, _cheese)
>
> Of course you can wrap up the import and _postimport in a single function:
>
> _magic_from_import('thingy', 'spam eggs cheese')
>
> Or use MacroPy to make the syntax nicer.
>
> Or, if even that's not good enough, write a simple token-processing import hook that finds "_import" tokens and converts them to calls to your wrapper function.
>
> Of course the farther you go down this path, the less readable your code becomes to someone who doesn't know about your function/macro/hook, but if there's really so much boilerplate that it's getting in the way, the tradeoff might be worth it.
>
... and then you decide, hey, let's just define __all__ and not worry
about adorning all those names with underscores, because the
definition of public vs private can be independent of the symbols
themselves.
ChrisA
More information about the Python-ideas
mailing list