Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Mel Newsgroups: comp.lang.python Subject: Re: Why do directly imported variables behave differently than those attached to imported module? Followup-To: comp.lang.python Date: Tue, 03 May 2011 13:00:28 -0400 Organization: Aioe.org NNTP Server Lines: 44 Message-ID: References: Reply-To: mwilson@the-wire.com NNTP-Posting-Host: Ako0BITcBw0jkGmD9p7rgQ.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Complaints-To: abuse@aioe.org User-Agent: KNode/4.4.8 X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:4556 Dun Peal wrote: > Hi! > > Here's the demonstrating code: > > # module foo.py > var = 0 > > def set(): > global var > var = 1 > > Script using this module: > > import foo > from foo import * > > print var, foo.var > set() > print var, foo.var > > Script output: > > 0 0 > 0 1 > > Apparently, the `var` we imported from `foo` never got set, but > `foo.var` on the imported `foo` - did. Why? They're different because -- they're different. `foo.var` is defined in the namespace of the foo module. Introspectively, you would access it as `foo.__dict__['var']` . Plain `var` is in your script's namespace so you could access it as `globals()['var']` . The values given to the vars are immutable integers, so assignment works by rebinding. The two different bindings in foo.__dict__ and globals() get bound to different integer objects. Note too the possible use of `globals()['foo'].__dict__['var'] . (Hope there are no typos in this post.) Mel.