473,324 Members | 2,473 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Initializing defaults to module variables

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)

My question is, how can I setup my program defaults so that they can
be overwritten by the configuration variables in the user file (and so
I don't have to scatter default values all over my code in try/catch
blocks)? Basically, I would like to be able to do something like this:

config.login = "noone"
config.password = "secret"
Apr 12 '06 #1
6 2185
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)

My question is, how can I setup my program defaults so that they can
be overwritten by the configuration variables in the user file (and so


You could use the ConfigParser module instead of putting your config in
a Python module. ConfigParser allows specifying defaults.

Kent
Apr 12 '06 #2
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 -+-
Apr 13 '06 #3
Burton Samograd wrote:
My question is, how can I setup my program defaults so that they can
be overwritten by the configuration variables in the user file (and so
I don't have to scatter default values all over my code in try/catch
blocks)?


The Django web framework happens to do something very like this.
Instead of 'import config' you have to do 'from django.conf import
settings', and you have an environment variable that allows you to
specify the user settings file, but otherwise I think it is pretty much
the same.

The guts of the mechanism is here:

http://code.djangoproject.com/browse...nf/__init__.py

It has quite a bit of custom Django stuff in there that you can ignore,
but I think the principles should apply.

Luke

Apr 13 '06 #4
Burton Samograd <kr**********@gmail.com> writes:
Is there a way to create a module namespace and populate it
before sourcing the file?


A reply to my own question, but I thought I would share the answer. I
got it to work with the following code:

import config
import sys
from posix import environ
sys.path.insert(0, environ["HOME"]+"/.program")
reload(config)

I have a file in my working directory that contains all the program
variables with default values called config.py, which is loaded at the
start, and then the user configuration directory is inserted into the
load path and then their config.py is loaded, which will then
overwrite the default values.

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #5
Burton Samograd wrote:
A reply to my own question, but I thought I would share the answer. I
got it to work with the following code:

import config
import sys
from posix import environ
sys.path.insert(0, environ["HOME"]+"/.program")
reload(config)

I have a file in my working directory that contains all the program
variables with default values called config.py, which is loaded at the
start, and then the user configuration directory is inserted into the
load path and then their config.py is loaded, which will then
overwrite the default values.


since you know the name of the config file you're looking for, you can
simplify (and unweirdify) your code a bit by changing your config file to
look like this:

# File: config.py

#
# configuration defaults

some_param = "value"
some_other_param = 1

#
# get user overrides

import os
try:
execfile(os.path.expanduser("~/.program/config.py"))
except IOError:
pass # ignore missing config file, but not syntax errors

# end of file

with this in place, you just have to do

import config

in any application module than needs to access the configuration data.

</F>

Apr 13 '06 #6
"Fredrik Lundh" <fr*****@pythonware.com> writes:
since you know the name of the config file you're looking for, you can
simplify (and unweirdify) your code a bit by changing your config file to
look like this:

# File: config.py

#
# configuration defaults

some_param = "value"
some_other_param = 1

#
# get user overrides

import os
try:
execfile(os.path.expanduser("~/.program/config.py"))
except IOError:
pass # ignore missing config file, but not syntax errors

# end of file

with this in place, you just have to do

import config

in any application module than needs to access the configuration
data.


nice, that looks to be just what I was looking for. thanks.

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
10
by: serge | last post by:
I am doing a little research on Google about this topic and I ran into this thread: ...
8
by: Weaver | last post by:
I'm new to Access 97. Where's the best place to initialize global variables that are established in the declarations area?
17
by: Calle Pettersson | last post by:
Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later... In Java, I would write something like public static void...
2
by: eriwik | last post by:
Given a simple class like class test { private: size_t size_; int* data_; public: test(size_t s) : size_(s), data_(new int { /* ... */ };
8
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine,...
8
by: John | last post by:
Hello, is there any compiler option for g++ for initializing static members of the class. Due to some unknown reason, static member in one of our c++ application is not getting initialized...
4
by: rshepard | last post by:
I'm stymied by what should be a simple Python task: accessing the value of a variable assigned in one module from within a second module. I wonder if someone here can help clarify my thinking. I've...
10
by: Jason Doucette | last post by:
Situation: I have a simple struct that, say, holds a color (R, G, and B). I created my own constructors to ease its creation. As a result, I lose the default constructor. I dislike this, but...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.