Re: Newbie: splitting dictionary definition across two .py files
- From: "Karthik Gurusamy" <kar1107@xxxxxxxxx>
- Date: 31 Mar 2006 12:44:39 -0800
Ben Cartwright wrote:
kar1107@xxxxxxxxx wrote:
I like to define a big dictionary in two
files and use it my main file, build.py
I want the definition to go into build_cfg.py and build_cfg_static.py.
build_cfg_static.py:
target_db = {}
target_db['foo'] = 'bar'
build_cfg.py
target_db['xyz'] = 'abc'
In build.py, I like to do
from build_cfg_static import *
from build_cfg import *
...now use target_db to access all elements. The problem looks like, I
can't
have the definition of target_db split across two files. I think they
reside in different name spaces?
Yes. As it stands, build_cfg.py will not compile to bytecode
(NameError: name 'target_db' is not defined).
Unless you're doing something ugly like exec() on the its contents, .py
files need to be valid before they can be imported.
Is there any way I can have the same
dictionary definition split across two files?
Try this:
# build_cfg_static.py:
target_db = {}
target_db['foo'] = 'bar'
# build_cfg.py:
target_db = {}
target_db['xyz'] = 'abc'
# build.py:
from build_cfg_static import target_db
from build_cfg import target_db as merge_db
target_db.update(merge_db)
Thanks; it works great.
I also found using import inside build_cfg.py also works.
#build_cfg_static.py:
target_db = {}
#.. other dict entry definitions
#build_cfg.py:
from build_cfg_static import *
#.. more dict entry definitions
But I think using two different dictionaries and merging as you have
suggested is a better approach than the above way of an import file
importing another file. But doing the dictionary merge may incur
additional performance cost; but for my dataset size, it should be
okay.
Karthik
--Ben
.
- References:
- Newbie: splitting dictionary definition across two .py files
- From: kar1107
- Re: Newbie: splitting dictionary definition across two .py files
- From: Ben Cartwright
- Newbie: splitting dictionary definition across two .py files
- Prev by Date: Re: Looking for a language/framework
- Next by Date: Re: Newbie: splitting dictionary definition across two .py files
- Previous by thread: Re: Newbie: splitting dictionary definition across two .py files
- Next by thread: Re: Newbie: splitting dictionary definition across two .py files
- Index(es):