How to make a variable's late binding crosses the module boundary?

Peter J. Holzer hjp-python at hjp.at
Mon Aug 29 14:45:12 EDT 2022


On 2022-08-29 11:40:33 +0100, Mark Bourne wrote:
> Jach Feng wrote:
> > Chris Angelico 在 2022年8月29日 星期一下午1:58:58 [UTC+8] 的信中寫道:
> > > On Mon, 29 Aug 2022 at 15:54, Jach Feng <jf... at ms4.hinet.net> wrote:
> > > > Sometimes I am wondering why "from x import y" hides x?
> > > > hum...can't figure out the reason:-)
> > > > 
> > > "from x import y" doesn't hide x - it just grabs y. Python does
> > > what you tell it to. :)
> > > 
> > But I had heard people say that "from x import y" did import the
> > whole x module into memory, just as "import x" did, not "grabs y"
> > only. Is this correct?
> 
> `from x import y` does import the whole module x into memory, and adds
> it to `sys.modules`.  But it only binds the name `y` in the namespace
> of module doing the import (and it binds it to the value of `x.y` at
> the time the import is done

I think this should be rephrased. "`x.y` at the time the import is done"
implies that at this time the name `x` does exist in the current
namespace.  Which then leads to the conclusion that this name must be
hidden later. But I don't think this is the case.

The module is imported but it isn't bound to any name in the current
(global) namespace (obviously there must be some variable bound to it, but
that's probably a local variable in the importer and it isn't called
`x`). Then the object bound to the name `y` in the loaed module is bound
to the name `y` in the current namespace.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20220829/c3019649/attachment.sig>


More information about the Python-list mailing list