how do python module variables work?

I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py, which is empty, and mdir/mymod.py, which is:

thenum = None def setNum(n): global thenum if thenum is not None: raise ValueError("Num already set") thenum = n def getNum(): if thenum is None: raise ValueError("Num hasn't been set") return thenum

First few use cases from the same file go according to expectation. This file is ./usage.py, the same folder mdir is in:

import mdir.mymod mdir.mymod.setNum(4) print mdir.mymod.getNum() from mdir import mymod print mymod.getNum() from mdir.mymod import * print getNum() try: setNum(10) except ValueError: print "YHep, exception"

The output is as expected:

4 4 4 YHep, exception

However, if I muck with the system path, then it looks like the module is imported anew:

#BEHOLD import sys sys.path.append("mdir") import mymod try: mymod.getNum() except ValueError: print "Should not have gotten exception" mymod.setNum(10) print mymod.getNum() print mdir.mymod.getNum()

That code, running after the previous code, yields:

Should not have gotten exception 10 4

What gives?

-------------Problems Reply------------

mymod and mdir.mymod are considered different modules - here's somewhat related discussion: http://code.djangoproject.com/ticket/3951

Explanation:

It's best to play with python interactive interpreter and see for yourself. I created directory (package) mydir under some directory and inside it two files (modules) - __init__.py and mymod.py, both empty. I started python inside of directory containing mydir. Now see what happens:

>>> import mydir.mymod
>>> from mydir import mymod
>>> mymod == mydir.mymod
True

Why are mymod and mydir.mymod considered the same thing? Well, both names refer to the same module object - modules equality is determined by their paths comparison:

>>> mymod
<module 'mydir.mymod' from 'mydir\mymod.py'>
>>> mydir.mymod
<module 'mydir.mymod' from 'mydir\mymod.py'>

Now, if I alter sys.path to contain mydir and import mymod in such a way that path of imported module will seem to be different:

>>> import sys
>>> sys.path.append( "d:/zrodla/stack/mydir" )
# note that importing mymod (and not mydir.mymod) prior to appending mydir to
# path would cause an error
>>> mymod2
<module 'mymod' from 'd:/zrodla/stack/mydir\mymod.pyc'>
>>> mymod2 == mydir.mymod
False

then resulting module objects will not compare equal. This way one module will be imported twice - it's normal and that's the way python works. Just remember that imported modules are identified by their paths - more specifically by 'dotted paths' I think - look at sys.modules keys:

>>> [x for x in sys.modules.keys() if "my" in x]
['mydir', 'mymod', 'mydir.mymod']

I hope it's clear now.

Category:python Views:0 Time:2010-08-24

Related post

  • How to access a python module variable using a string [ django ] 2011-08-19

    I have a django application, with a module called "app" Now this module has a file called "urls.py" which has a variable called "HOME_URL" What I'm trying to do ? app_label = "app" url = __import__(app_label).urls.HOME_URL print url That obviously do

  • Python: How to make a cross-module variable? 2008-09-26

    The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense

  • Python and Eclipse: How to use interactive console after running a module, with the module variables and functions 2010-04-14

    Let's consider 3 situations: 1) I write a pyhon module in Eclipse (pydev) and run it Ctrl-F11. The module runs and I don't have any control or access (AFAIK) to the module variables and functions. 2) I have defined a python interpreter as an external

  • Python module get top scope variables 2011-02-08

    Hey, in my python modules (written in python) I want to be able to access the variables from the top level scope, that is, the file that is calling the modules. How would I go about doing this? Thanks. --------------Solutions------------- In general,

  • Help with accessing module variable inside Python function? 2011-08-10

    I have the following function in a Python module called dictbuilder.py: def my_dictbuilder(reader_o, writer): fieldnames = ('name', 'number') reader = csv.DictReader(reader_o, fieldnames = fieldnames, delimiter="\t") my_dict = {} id = 0 for row in re

  • Python module not working (not able to import) even after including it in PATH variable 2012-02-04

    I have one testing module that I want to use for android testing. I have the files but there is no installation file for it, so I added the module to PATH variable, even then it doesn't work I try to import it. Any way to make it work. Do I have to p

  • Python module for multiple variable global optimization 2010-11-19

    I have been looking for a python module that implements the common techniques of global optimization (finding the global minimum of a function in N dimensions) without success. If you heard about a simulated annealing or genetic algorithm implementat

  • listing all functions in a python module 2008-09-26

    I'm not a pythonista, so I'm not sure if this is really obvious or not. I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it so I can call the doc function on each one. In rub

  • Python module dependency 2008-10-01

    Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CP

  • How to avoid computation every time a python module is reloaded 2008-10-12

    I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I s

  • How do I calculate the date six months from the current date using the datetime Python module? 2009-02-13

    I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this? The reason I want to generate a date 6 months from the current date is to produce a Review Date.

  • Python module for editing text in CLI 2009-06-01

    Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable? At the moment I have users enter stuff in using

  • How to import python module in a shared folder? 2009-07-28

    I have some python modules in a shared folder on a Windows machine. The file is \mtl12366150\test\mymodule.py os.path.exists tells me this path is valid. I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is va

  • Is it possible to utilize a python module that isnt installed into the python directories in linux? 2009-07-31

    I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there

  • What is the most compatible way to install python modules on a Mac? 2009-07-31

    I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble. On the Mac, I'm used to u

  • How to encapsulate python modules? 2009-09-18

    Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file? My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server su

  • Lazy module variables--can it be done? 2009-09-22

    I'm trying to find a way to lazily load a module-level variable. Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a DOWNLOAD_FOLDER_PATH module variable. Unfortunately, iTunes won't tell you where its download fo

  • Python: static variable decorator 2009-10-23

    I'd like to create a decorator like below, but I can't seem to think of an implementation that works. I'm starting to think it's not possible, but thought I would ask you guys first. I realize there's various other ways to create static variables in

  • How to develop a Python module/package without having to restart the interpreter after every change? 2010-01-01

    I am developing a Python package using a text editor and IPython. Each time I change any of the module code I have to restart the interpreter to test this. This is a pain since the classes I am developing rely on a context that needs to be re-establi

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.060 (s). 11 q(s)