Should I have put a smiley on some of those posts ? :-)
The point of my "UGLY KLUDGE" post was to ask if there was
a LESS obfuscated way to do it. In that case, the only
method I discovered ( to overlay module name space )
sort of disgueted me into a profoundly ironic mode!
Actually, I had considered another equally ugly, but less
interesting method: To search along sys.path for the
next occurance of module.py, create a symbolic link
in the current directory, "./oldmodule.py", pointing
to the old module, and then import it as oldmodule.
But that was a bit too posix specific.
Re: __name__ :
The problem there was wanting to do a getattr( module, attr ) without
hardwiring the current name of the file into the modules code.
[ Of cource, I'ld have to do an eval of __name__ to get the
module OBJECT. ]
The fact that __name__ is left out out of the namespace seems to be
the exception to the pattern. Is there a reason for it to behave
differenly that the other attributes ?
Also - in the context of the other name space questions:
Someone else suggested "import xxx from pathname" -
I was also considering other modifications of import, but any
change that would make the module name more dynamically evaluated,
would require that capability.
In any case, for the problem that inspired the question, I at first
tried:
import __main__
def getopt2( name ):
if name in dir(__main__.options) : return getattr(__main__.options, name )
[ where the file was options.py ]
and later decided it was neater to separate that function into a
separate module that imported 'options' :
This is intended as a way of setting and getting global options
for the whole program/session ( like DEBUG, for example ).
[ and it still contains it's own debug print statements at the present!]
- Steve M.
### ------ options.py ------ ######
# if posix.environ supported then look for any environ variables
# that start with "PYTHON". For each, strip off the leading "PYTHON"
# and try to create a symbol by constructing and exec-ing an assignment:
# first with the value itself, then try it quoted.
try:
from posix import environ
for env in environ.keys():
if env[:6] == 'PYTHON' :
print '{'+env+'}', ':', environ[env]
try:
e = env[6:] + ' = ' + environ[env]
print 'Try: exec:',e
exec(e)
except (NameError, SyntaxError):
e = env[6:] + ' = \'' + environ[env] +'\''
print 'Try: exec:', e
exec( e )
del e
else:
del env
del environ
# clean up all of the extraneous symbols.
except ImportError:
pass
#
# set any global options here:
#
test='Testing: 1,2,3...'
OK=1
##### --------- getoptions.py ---------
import options
#
# options can be accesses by:
# "options.name" or "options.__dict__['name']" or "getattr( options, 'name' )"
# but all of the above will create an exception if it doesn't exist.
#
#
def getopt( name ):
return ((name in dir(options)) and getattr( options, name ) )