Adam Smith
Adam Smith

Reputation: 54213

from package import * as _

My project has a number of click functions that is imported in my entrypoint with:

import package.module as _

however I'm implementing a plugins folder that allows user-created code to hook into the same utility. package/plugins/__init__.py is dynamically populating its __all__ so I can from package.plugins import *.

I don't particularly want all those names polluting my namespace, though, I'm only using the import for its side effects. Is there a way to import * as _?

Upvotes: 1

Views: 2359

Answers (2)

user2357112
user2357112

Reputation: 280973

If you're using the import * for the side effects specific to import *... well that's kind of a weird thing to do, but you can use __import__ with fromlist=['*'] to perform those side effects without any namespace pollution:

__import__('package', fromlist=['*'])

This will autoload all submodules in a package's __all__ list, unlike a plain import package.

Upvotes: 1

Picachieu
Picachieu

Reputation: 3782

If you don't want the contents of a module to pollute your program, you can just import the module:

import module

or import as:

import module as name

import * is meant for the times when you don't want the module to be in it's own namespace. Doing this:

from module import *

automatically puts everything from module into the scope the import is in (usually the global scope). from module import * is a special type of from module import something, which imports only the specified contents into your program.

Be aware that submodules can be imported the same way as normal modules, i.e. import os.path as somemodule is legal.

Upvotes: 1

Related Questions