Cleb
Cleb

Reputation: 25997

How to define the imports from a module?

I have a directory structure like this:

└── stuff
    ├── __init__.py
    └── substuff
        ├── imp.py
        └── __init__.py

stuff/__init__.py looks as follows:

from stuff.substuff.imp import foo, bar

and stuff/substuff/__init__.py like this:

from stuff.substuff.imp import foo, bar

__all__ = [
    'foo',
    'bar'
]

stuff/substuff/imp.py contains

import pandas as pd
import numpy as np

__all__ = ['foo', 'bar']


def foo():
    return {'foo': np.sqrt(2)}


def bar():
    return ('bar', 'xyz')


def _helper():
    return True

If I now do

from stuff.substuff import imp

and check what is available for imp, I see bar, foo, but also pd and np.

How can I achieve that the user only sees bar and foo, but not pd and np? One solution seems to be to import them as _pd and _np, but I am wondering whether there is a "prettier" solution than this.

Upvotes: 3

Views: 100

Answers (1)

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8029

First of all, note that __all__ doesn’t prevent any of the module symbols (functions, classes, etc.) from being directly imported. Check this amazing article for more details. It only sets behavior for from stuff.substuff.imp import *, not explicit module import (docs).

This statement will only import foo and bar as you expect:

from stuff.substuff import *

Also you've already limited imports directly from substuff package to foo and bar:

from stuff.substuff import foo  # successfully imported
from stuff.substuff import pd  # import error

Upvotes: 1

Related Questions