Split "dict" definition up between files
I'd like to define the contents of a large dictionary object up between files. I'm wondering if this is possible in python.
Ideally, this is what I'd like to do:
Main File: (dict_object_main.py)
# File name: dict_object_main.py
import dict_object_sub1
import dict_object_sub2
dict_object = {}
d开发者_JAVA技巧ef doSomeStuffWithTheDictObject:
...
return
1st File that adds a lot of stuff to "dict_object": (dict_object_sub1.py)
# File name: dict_object_sub1.py
from dict_object_main import dict_object
dict_object['sub1'] ={
'property1':'value1'
...
,'property9999':'value9999'
}
2nd File that adds a lot of stuff to "dict_object": (dict_object_sub2.py)
# File name: dict_object_sub2.py
from dict_object_main import dict_object
dict_object['sub2'] ={
'property1':'value1'
...
,'property9999':'value9999'
}
I have something similar set up in javascript. Is it ok to do it this way in Python or should I be doing it differently?
Thanks!
Edit: The first part to my previous answer was wrong. The lesson I learned is don't have circular dependencies. The following is correct:
Another option is to try this in the main file:
from dict_object_sub1 import dict_object_sub1
from dict_object_sub2 import dict_object_sub2
dict_object = {}
dict_object.update(dict_object_sub1)
dict_object.update(dict_object_sub2)
Then in both of the sub files do something like this:
# dict_object_sub1.py
dict_object_sub1 = {...}
You may want to use the update
method instead.
# Same for dict_object_sub1.py or dict_object_sub2.py
from dict_object_main import dict_object
dict_object.update({
'prop1': 'val1',
# ...
})
Note: I don't think it makes much sense to split the declaration out on two different files. The final memory occupied by the dictionary will be exactly the same in both cases.
Edit: As daveydave400 pointed out in his answer, the importing order is wrong too.
You need at least 3 distinct files (or doing the updates in the importing module):
A dict_declare.py file, where you declare your dictionary:
dict_object = {}
A file for each partial dictionary declaration:
from dict_object import dict_object dict_object.update({ 'prop1': 'val1', # ... })
Your main file:
from dict_declare import dict_object import dict_object_sub<n> # ... repeat def doSomeStuffWithTheDictObject: ... return
精彩评论