Carson McManus
Carson McManus

Reputation: 344

How do you avoid importing a modules imports? Can you dynamically generate `__all__` at runtime?

I'm working on a large project that imports a lot of stuff. I have modules that import modules with from ... import *, and I want to avoid polluting module level variables when doing that.

For example:

module A:

import foobar

def foo():
    pass
bar = 10

module B:

from A import *

# here, foobar is present, but I don't want it to be.

Obviously, the solution is to use __all__. So now it looks like this:

module A:

import foobar

def foo():
    pass
bar = 10

__all__ = ["foo", "bar"]

module B:

from A import *

# here, foobar is no longer present

But this is tedious and time consuming.

Is it possible to generate __all__ dynamically, at runtime, without explicitly typing out all of the functions/classes that I want to export in a list?

Upvotes: 1

Views: 82

Answers (1)

Copperfield
Copperfield

Reputation: 8510

yes, you can generate your __all__ list dynamically with the help of dir

module A:

import foobar

__exclude_from_all__=set(dir()) #everything prior to this line will be here

def foo():
    pass
bar =10

#a second call to dir now will include everything we defined after the first one
#and can be used to filter out the undesired stuff
__all__ = [ x for x in dir() if not (x.startswith("_") or x in __exclude_from_all__) ]
del __exclude_from_all__

Upvotes: 3

Related Questions