Proposal: private keyword for import statements to hide module dependencies

Bjørnar Remmen via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>
Hi, this is my first time here on the mailing list. 

I would like to open up for a discussion on how we can introduce a way to hide imports.
I am proposing the introduction of an optional, non-breaking keyword, private, to be used when importing a file. The goal is to allow developer to hide internal dependencies and  prevent them from leaking into the module's public namespace.

Under the current system, any object imported into a module's top-level scope becomes an accessible attribute of that module.
module/math.py
'''
import numpy as np

def calculate_mean(data: np.ndarray) -> float:
    return np.mean(data)
'''
The issue is that when a user imports this module, the import is exposed.
'''
import module.math
# This is valid, even though 'np' is an internal detail:
# module.math.np
'''

While we have some conventions, we do not have explicit hiding of such modules. 
We have one solution, which is more like a convention

'''
import numpy as _np

'''
This hides it for common usage and signals to the developer that it is private.

__all__ works for wildcard imports, but not for standard imports. 

I suggest adopting a solution similar to what has been implemented in swift, which is to introduce a modifier keyword:
'''
private import numpy as np

def calculate_mean(data: np.ndarray) -> float:
    return np.mean(data)

'''

Internally in the file np is accesible, but when importing the file it is not accesible.

Expected behaviour:

import module.math	
module.math.np
This  raises an AttributeError

from module.math import np	raises an ImportError

from module.math import calculate_mean	Succeeds
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.