Welcome, guest | Sign In | My Account | Store | Cart

Use this code in your module to prevent people using the "from foo import *" syntax with your module.

Python, 4 lines
class __all__(object):
    def __getitem__(self, _):
        raise ImportError("Star imports not supported")


Alan Franzoni 13 years, 11 months ago  # | flag

I don't think it's a good idea. You're quite changing the way the language works - if you think some names shouldn't be exported, just set the __all__ name with a list of names that should.

Also, if anybody wants to check for the public API of your module must then resort to its full scope, since there's no way to check __all__ (iterating over __all__ gives the very same importerror as doing the star import).

Benjamin Peterson 13 years, 11 months ago  # | flag

Don't use apply as a decorator. It's a cute trick, but apply is a deprecated function.

Mike Graham (author) 13 years, 11 months ago  # | flag

Benjamin, so you are saying I should change the first line to



Mike Graham (author) 13 years, 11 months ago  # | flag
Chris Jones 13 years, 10 months ago  # | flag

Just set __all__ to an empty list if you don't want to export anything. What do you gain by causing error in end-user's stack? FYI you also break the help() feature which now does not know which methods are meant to be public..

Created by Mike Graham on Fri, 21 May 2010 (MIT)
Python recipes (4591)
Mike Graham's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks