Say I have a file called settings.py and it's content is the following:
{
"translate_tabs_to_spaces": True,
"word_wrap": "true",
"font_face": "Monaco",
"font_size": 14.0,
"highlight_line": True,
"ignored_packages":
[
""
],
"what": '''
This is python file, not json
'''
}
How can I get it into a dict called settings in my main app file app.py?
Thanks.
Why not name that dict say settings
and than just import it from settings.py eg
settings.py
settings = {} # fill with your data
use it like this
>>> from settings import settings
>>> print settings
{}
Alternate solutions is to just add variables at settings module level and use them directly, why you need a dict? eg
settings.py
translate_tabs_to_spaces = True
# more settings
use it like this
>>> import settings
>>> settings.translate_tabs_to_spaces
True
You can use ast.literal_eval()
to do this safely.
import ast
data="""\
{
"translate_tabs_to_spaces": True,
"word_wrap": "true",
"font_face": "Monaco",
"font_size": 14.0,
"highlight_line": True,
"ignored_packages":
[
""
],
"what": '''
This is python file, not json
'''
}\
"""
print(ast.literal_eval(data))
Giving us:
{'what': '\n This is python file, not json\n ', 'font_size': 14.0, 'translate_tabs_to_spaces': True, 'font_face': 'Monaco', 'word_wrap': 'true', 'highlight_line': True, 'ignored_packages': ['']}
Given the new comment from the asker that suggests that he wants to be able to use ...
in his config, ast.literal_eval()
will not be suitable, as it can't handle ellipses.It's not quite clear if this is what he meant, and this is still a good answer to the question that was asked.
Turns out the asker was talking about triple quoted strings, which are handled by this correctly.
Give the settings dict a name in the settings module then import the settings module into your module and load it into a variable like
import settings
your_settings = settings.settings_dict
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.