Symbolic imports and manipulation of the namespace?

John Bell jbell at iinet.net.au
Wed Mar 27 03:14:53 EST 2002


VanL wrote:

> Hello,
> 
> I was recently solving a problem which required that the config file 
> (just a python file) lie outside of the pythonpath.  Is it possible to 
> do symbolic importation of a module?
> 
> For example, I had:
> 
> # cfgpath is passed in on the command line
> cfgpath = os.path.basename(cfgpath)
> sys.path.insert (0, cfgpath)
> import sc_cfg     #Hardcoded config module name!
> 
> 
> How do you do this:
> 
> # cfgpath is passed in on the command line
> cfgpath, cfgfile = os.path.split(cfgpath)
> sys.path.insert (0, cfgpath)
> import cfgfile     #Hardcoded config module name!
> 
> So that any file name (ending with .py, of course, but that's another 
> matter) could be the configfile?
> I tried the above, but I got an ImportError (no module named cfgfile)


Basically it depends what you want to do with the file.  If you simply 
want to execute it in-line (which given that it's a config file is most 
probably the case) then use execfile.  This by default executes the file 
within the namespace of the caller, so is somewhat like an include or 
import statement in other languages.  NOTE THE CAVEAT RE EXECUTION 
WITHIN A FUNCTION BODY.  Check the manual page re manipulation of the 
namespace.

If the file has classes you want to create or functions you want to call 
you should use __import__.  The idea is to put your file (say myfile.py) 
in your search path.  Then if you want to create an instance of myobject 
defined in myfile.py:

modname='myfile'
objname='myobject'
_module=__import__(name)
_class=getattr(_module,objname)
_object=_class(instantiation parameters)

where _object is the instance.  Function invocation works in a parallel 
fashion.  Once again, see the manual page re namespace manipulation.

John


> 
> Thanks,
> 
> Van
> 
> 




More information about the Python-list mailing list