Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


The 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-fr...


Linters 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.


You 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


Any 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.


Python 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




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: