Lecture 2 addendum: importing and using your own code

This year, lecture 2 didn't go over how to import your own code via import as I wanted to keep things simple and we'll do modules and namespaces later. However, if you're interested here's an example, the files are in the lecture 2 lecture notes in a folder called import mystuff example .

 Assume you have a .py file called mystuff.py with this code:
1
2
3
4
5
6
# Test for importing your own code "module"
# This should be placed in a file called mystuff.py in the same folder as my_import_example.py 

# assign a value to m
m = 123
print "value of m printed from inside the imported module:", m

The main .py file (I'll call it import_mystuff_example.py), looks like this:
1
2
3
4
5
6
# main program for import mystuff.py example

# imports the content if the file mystuff.py (in same folder, without the .py)
import mystuff # must be in same folder as this script is executed in
print dir(mystuff)  # list what's defined in mystuff.py
print mystuff.m # print the value of m defined within this file

Running mport_mystuff_example.py shows this:
================================ RESTART ================================
value of m printed from inside the imported module: 123
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'm']
123

import_mystuff_example.py's import will look for a file mystuff.py (in the same folder or in the official python package folder) and create a .pyc file (which is a byte-code representation of mystuff.py and the reason you need to use reload). Anything defined in the "importee" (here mystuff.py just creates a variable called m with value 123) will be available to importer. print dir() will list this content, the __ stuff is internal stuff but mystuff.pys variable m is shown at the end.

In order to distinguish mystuff.py's m from other variables called m, we need to use its full name when printing it after the import with mstuff.m


It should be noted that the import not only grabs the definition of variables (or object classes, etc.) but also any assignments that were done in the module (here we used m = 123 inside mystuff.py). Maybe you want to make changes to mystuff.m (add new variables, change values), and use them while the interpreter that did the import earlier is still running, you need to user the reload function, which will re-create the mystuff.pyc file and really read any changes you made to mystuff.py. Simply doing a second import won't force a true re-import (that has to do with efficiency), you need to use reload().



After reload() the new value for m (456) comes through:



However, if you kill the python interpreter that is running your import_mystuff_example.py main program and re-run it,  a new interpreter os created which will read in your new mystuff.py's content.

More on importing here: http://docs.python.org/library/imp.html#module-imp

No comments:

Search This Blog