4 ms·
Side question: how do you prevent import statements from being imported by "from lib import star"? (Without explicitly mentioning all the stuff that is not impo
by amelius 5y ago
Side question: how do you prevent import statements from being imported by "from lib import star"? (Without explicitly mentioning all the stuff that is not import statements).
For example, this is mymod.py:
import numpy as np
def f(x): return 2*x
And here it is imported:
from mymod import *
f(10) # Works as expected.
np.sum([10, 20]) # Works, but shouldn't work.
- connorbrinton 5y agoThe best you can do (without doing crazy introspection) is to set `__all__` in `mymod`. It still requires listing everything you want to be exported from `mymod`, but at least you only need to do it once. Docs: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package https://docs.python.org/3/tutorial/modules.html#importing-fr...
- formerly_proven 5y agoLinters will also complain about importing stuff that's not listed in a module's __all__, so it's overall good API hygiene to have one.
- comradesmith 5y agoPython modules can define a list named `__all__` which of present will define the behaviour of importing “everything”. The `from x import y` syntax is unaffected
- qbasic_forever 5y agoAny non-trivial python module is going to be broken up into multiple files and have an __init__.py which you can explicitly define what's imported and exposed. You can hoist a single file module into a folder-based module if you need direct control and don't want to split it apart into multiple files yet too.
- ciupicri 5y agoYou could use names starting with _ (underscore) for things that you don't want to export. Your module would look like this: import numpy as _np # numpy will be hidden def f(x): return x * 2 def _g(x): return _np.array([x, x]) # _g is a non-public function