Avoid submodules and external packages in the module namespace

I am writing a module to load a dataset. I want to keep the interface / API as clean as possible, so I made the internal functions and variables hidden by prefixing their names with __

. Stunning. My module, however, is importing other packages (for example numpy

) that are still showing up in the module namespace, how can I avoid this?

i.e. my file looks something like this:

Loader.py:

import numpy as np

__INTERNAL_VAR1 = True
EXTERNAL_VAR = True

def loadData():
    data = __INTERNAL_FUNC1()
    ...
    return data

def __INTERNAL_FUNC1():
    ...
    return data

      

and when i import my module np

:

> import Loader
> Loader.[TAB]
  Loader.EXTERNAL_VAR   Loader.loadData   Loader.np

      

+3


source to share


1 answer


If the autocomplete you are using is correctly implemented, it should honor the __all__

modules attribute if set.

Add a list of all the names your module exports with this name:

__all__ = ['loadData', 'EXTERNAL_VAR']

      



The variable is __all__

used to determine what names are imported if you use a wildcard from modulename import *

, and also a function help()

when documenting your module.

There is no point in using double underscore names as global names; it is the only underscore at the beginning that marks such names as "internal" (by convention).

+2


source







All Articles