[Tutor] imported module/global

Cecilia Alm ebbaalm at uiuc.edu
Sun Apr 15 23:46:16 CEST 2007


Well, your example still seems to be about accessing or modifying a
global variable *within* its own module. Then it can't hurt to prepend
'global' even when just accessing, right? (even if not *necessary*,
one could argue make the code clearer).

But, my question related specifically to another case:  when another
module import a second module and the importing module tries to access
and modify the second module's "global" variable, which Kent's post
explained is really a module attribute. Then, the dot notation seems
needed.

(Maybe its my use of 'global' in this context which causes misunderstanding?)



2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> * Cecilia Alm <ebbaalm at uiuc.edu> [070415 23:19]:
> > 2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> > >* Cecilia Alm <ebbaalm at uiuc.edu> [070415 18:21]:
> > >> If a module "x" imports module "y" with a global variable "z", then
> > >> this global can be referred or assigned to in "x" with the syntax
> > >> "y.z" (no "global" keyword preceding) and changes are accessible to
> > >> class methods in "y" referring to "global z".
> > >
> > >Well, you don't need the global statement for accessing z. You need it
> > >for modifying it, or Python will assume that you are working with a
> > >local variable z.
> > >
> >
> > Hm, I'm confused by your post. Within the global's module, the "global
> > z" syntax works for bothh modifying and accessing, and makes the code
> > clearer to read in my opinion. (Although, it may not be needed when
> > accessing or when modifying mutable types.)
> Well, the global is not needed for accessing the name.
>
> And the assume it's a local variable is meant serious:
>
> >>> def x():
> ...     z += 1
> ...
> >>> x()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in x
> UnboundLocalError: local variable 'z' referenced before assignment
>
> It's one of the more baffling errors for newbies.
>
> The real reason is important to understand, it explains things like
> self. and global:
>
> *) when accessing a name, it's easy to try out multiple namespaces
> till you find the correct one.
> *) when reassigning a name, it's way harder, because you cannot
> automatically guess which namespace should be used.
>
> That's the reason why you need global statement, which makes
> assignments to a name go to the module namespace. And that's one of
> the reasons, why instance variables are accessed explicitly as self.name.
>
> Andreas
>


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute


More information about the Tutor mailing list