[Tutor] 'source' in python or preloading variables

Kent Johnson kent37 at tds.net
Sun Nov 4 14:25:13 CET 2007


John wrote:
> Does anyone know why the script below works fine (in regards to the 
> 'source function') but when I try to uncomment the line from mymod 
> import source and use it that way without defining the function in the 
> script, I get an error that N_id does not exist. It must have something 
> to do with namespace and global variables I don't understand...

I think the exec must be using the namespace of the current execution 
context rather than the lexically scoped namespace.

Why do you need to create these variables? Could you just create a 
dictionary with the name / value pairs and use that?

Generally in Python it is better to find a solution with a dict than to 
try to create named variables.

Kent

>  
>  
> #!/usr/bin/env python
> 
> from PyF import *
> #from mymod import source
> vList=['N_id','Nlat','Nlon','Nelv']
> ###### FUNCTION #########
> def source(filename, vList):
>         """ Reads a filename, collects variabls in file, and returns 
> variables.
>         Usage: source(filename, vList) where vList is a list of variables.
>         
>         """
>         import re
>         # Read the file
>         fid=open(filename,'r')
>         lines = fid.readlines()
>         fid.close()
>         #how many variables
>         ns=len(lines)/len(vList)
>         #predefine the varibles
>         for v in vList:
>                 exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
> 
>         # Make it python friendly: put all values in 'single quotes'
>         cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v 
> in lines])
>         exec(cmd)
>         for v in vList:
>                 exec( "global %s ; %s = %s[1:]" % (v,v,v) )
> 
> 
> source('sites_ALL',vList)
> 
> 
> for s in N_id:
>         fw=stnWeb(s)
>         fw.mkStnBase()
> fw.mkWebBase()
>  
>  
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list