help on "from deen import *" vs. "import deen"

Erik python at lucidity.plus.com
Tue Nov 15 17:16:07 EST 2016


On 15/11/16 14:43, Michael Torrie wrote:
> As you've been told several times, if you "import deen" then you can
> place a new object into the deen namespace using something like:
>
> deen.foo=bar
>
> Importing everything from an imported module into the current module's
> namespace is not the best idea

But "from foo import *" is not importing "everything". It's the opposite 
- it's importing everything _that the module wants to explicitly expose_ 
(i.e., a subset of everything ;)).

It *used* to be everything in the module's namespace, but then the 
possibly misnamed "__all__" magic variable made it a subset of whatever 
the module's author wanted to expose.

However, "import foo" _does_ import "everything", and also gives the 
importer the power to re-bind names within that module's namespace too 
(which is the crux of the original question). This is not usually a good 
thing unless the importing module is incestuous with the imported module.

So this brings up another point - not sure if it has been made before: 
should a module have a way of *not* allowing an importer to re-bind its 
local bindings?

For example, something like a "__bindable__" variable such that all 
names not included may not be bound by any other module? And/or 
something like an "__export__" variable that says what gets exposed to a 
simple "import foo" (sometimes one might want to "import foo" and 
sometimes "from foo import *" for namespace reasons, but why should 
those two statements import different things)?

E.



More information about the Python-list mailing list