Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid sub-modules and external packages in a module's namespace

I'm writing a module to load a dataset. I want to keep the interface/API as clean as possible - so I've made internal functions and variables hidden by prefacing their names with __. Awesome. My module, however, imports other packages (e.g. numpy) which still appear in my module's namespace, how can I avoid this?

i.e. my file looks something like:

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 is exposed:

> import Loader
> Loader.[TAB]
  Loader.EXTERNAL_VAR   Loader.loadData   Loader.np
like image 502
DilithiumMatrix Avatar asked Dec 21 '14 02:12

DilithiumMatrix


1 Answers

If the autocompletion you are using is correctly implemented, it should honour the __all__ attribute of modules, if set.

Add a list of all names your module exports in that name:

__all__ = ['loadData', 'EXTERNAL_VAR']

The __all__ variable is used to determine what names are imported if you use a from modulename import * wildcard import, as well as by the help() function when documenting your module.

There is no point in using double-underscore names as globals; it is a single underscore at the start that marks such names as 'internal' (by convention).

like image 123
Martijn Pieters Avatar answered Sep 23 '22 12:09

Martijn Pieters