The intention is to access from a file (called, say, " index.py
") to the variables defined in another (for example, " config.py
" ).
That is, import, to one file, the variables of the other.
Ok, these are the contents of the files:
[ config.py
]
# encoding: utf-8
_root_tit = 'Título de la Aplicación'
_root_w = 1025
_root_h = 600
_root_bg = 'black'
_db_data_conn = {'db_name': 'db_miBase', 'password': 'xxxx', 'charset': 'utf8', 'use_unicode': True, 'user': 'usu_miBase'}
[ index.py
]
# encoding: utf-8
# Recuperando ENTORNO
#-----------------------------------------
from config import *
# Recogiendo datos
#-----------------------------------------
print('o> _root_tit: {}'.format(_root_tit))
print('o> _root_w: {}'.format(_root_w))
print('o> _root_h: {}'.format(_root_h))
print('o> _root_bg: {}'.format(_root_bg))
print('o> _db_data_conn: {}'.format(_db_data_conn))
In principle, this way, it should work since, of the file " config.py
" ( from config
) I import all its content ( import *
). In this case, all its variables. It is not like this?
And, besides, as I had learned (unless I'm wrong), with this way of importing, you can call the name of the variable directly, for example, _root_tit
, without having to precede the name of the variable for the file that is imported, that is, config._root_tit
.
Or is it that I'm wrong?
Well, when executing " index.py
" in the terminal, I get the ERROR that the variables are not defined. Already, not finding the definition of the first variable called with the print()
from the " index.py
", it stops.
" Mensaje de Error
"
NameError: name '_root_tit' is not defined
On the other hand, if that works, if I substitute the way to import this:
from config import *
to this:
import config as cfg
Of course, then, when calling each imported variable, I have to put:
cfg.variable_que_sea
So, the question is:
Why do you get the variables to import with import config as cfg
and not with from config import *
? Would something be missing to get through from config import *
?
I await your clarifying answers. Thank you. Greetings.
EXTRA NOTE: running on Ubuntu 16.04 with Python 2.7 (but, I suppose, this can also be applied to versions 3.x).