Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python import module imports when importing *

Let's say I have a file where I'm importing some packages:

# myfile.py
import os
import re
import pathlib

def func(x, y):
    print(x, y)

If I go into another file and enter

from myfile import *

Not only does it import func, but it also imports os, re, and pathlib,

but I DO NOT want those modules to be imported when I do import *.

Why is it importing the other packages I'm importing and how do you avoid this?

like image 417
Zack Plauché Avatar asked May 14 '26 22:05

Zack Plauché


1 Answers

The reason

Because import imports every name in the namespace. If something has a name inside the module, then it's valid to be exported.

How to avoid

First of all, you should almost never be using import *. It's almost always clearer code to either import the specific methods/variables you're trying to use (from module import func), or to import the whole module and access methods/variables via dot notation (import module; ...; module.func()).

That said, if you must use import * from module, there are a few ways to prevent certain names from being exported from module:

  1. Names starting with _ will not be imported by import * from .... They can still be imported directly (i.e. from module import _name), but not automatically. This means you can rename your imports so that they don't get exported, e.g. import os as _os. However, this also means that your entire code in that module has to refer to the _os instead of os, so you may have to modify lots of code.

  2. If a module contains the name __all__: List[str], then import * will export only the names contained in that list. In your example, add the line __all__ = ['func'] to your myfile.py, and then import * will only import func. See also this answer.

like image 52
Green Cloak Guy Avatar answered May 16 '26 12:05

Green Cloak Guy