Initializing defaults to module variables
Eric Deveaud
edeveaud at pasteur.fr
Thu Apr 13 04:20:14 EDT 2006
Burton Samograd wrote:
> Hi,
>
> I'm writing an app that stores some user configuration variables in a
> file ~/.program/config, which it then imports like so:
>
> import sys
> from posix import environ
> sys.path.append(environ["HOME"]+"/.program")
> import config
>
> I can then access the configuration through code like:
>
> login(config.username)
better use some plain text configuration file
check ConfigParser documentation.
> So I guess the real question is:
>
> Is there a way to create a module namespace and populate it
> before sourcing the file?
if you take a look at how naming space is affected by the variants
"from module import *" and his conterpart "import module", you will have your
answer.
shortly
if you use "import foo" all the variables/class/functions comming from the
module foo are located in a globlal space dictionary named foo
if you use "form foo import *" all variables/class/functions comming from the
foo module are located in gloabal space naming dictionary.
try this
-=-=-=-=-=-=- consider module foo.py -=-=-=-=-=-=-
my_var = "my var from foo"
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> print my_var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'my_var' is not defined
and now
hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo import *
>>> print my_var
my var from foo
this will lead to a solution regarding your problem
hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> my_var = 'some default value'
>>> from foo import *
>>> print my_var
my var from foo
once again, I bet your best choice will be to have some plain text config file
Eric
--
Je voudrais savoir s'il existe un compteur de vitesse (?) pour savoir
à quelle vitesse on est réellement connecté au FAI et surtout si une
telle bête existe... où la trouver.
-+- RJ in: Guide du Neuneu d'Usenet - Baisse la tête et pédale -+-
More information about the Python-list
mailing list