[Tutor] newbie Python Modules

Alan Gauld alan.gauld at btinternet.com
Tue Jun 17 01:47:02 CEST 2008


"Guess?!?" <wtfwhoami at gmail.com> wrote

> *Module Name eli.py*
> x = 0
> y = [1, 2]
>
> def whitney():
>     print 'whitney'
>
> def printValues():
>     print x , y

> *When I imported the Module*
>
> from eli import x, y, printValues

Note that by doing this you are not really importing the module
but the names from the module into your name space.

> printValues()
> y[0] = 'cat'

This is changing the value of the y variable which is in the
eli module.

> x = 'dog'

This is creaating a new x value in your local namespace.

> printValues()

This prints the values from the eli module.

> Running module "eli"
>
> 0 [1, 2]
>
> 0 ['cat', 2]

x is unchanged at zero.
y is also unchanged but the content is changed

> Is it because x = 'dog' is local variable and y being
> a list is a mutable object that is changed

Yes, although being picky about the term local its not
strictly true since local means inside a function or method
In your case you created a new global (ie module scope)
variable x which masked the imported one.

> Also once we reload the module .... every value reverts to its 
> original
> value .. Am I Right?

Yes, but you have not "loaded" the module yet, only the
names from within it.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list