Reputation: 927
In Lua script, when i have to wirte too many lines like:
obj.age=17
obj.name="jack"
obj.country="US"
...
obj.weight=100
I can use _ENV
to simpify the code:
_ENV=obj
age=17
name="jack"
country="US"
...
weight=100
Namely, I can avoid typing obj.
repeatedly, is there a way in python to do like this? I searched on net buf found nothing.
I need to use python script as a configuration file, and the latter format seems better.
Upvotes: 2
Views: 159
Reputation: 4964
You really asked two questions in one.
For the second about storing configuration, you can
write your vars in say, a 'config.py' module. Then import config as cfg
and manipulate using cfg.
qualified names. You can also from config import *
for direct use but that's not recommended and you loose write capability in the original config module. They are copied into current namespace, not linked.
simply use a dictionary to hold your settings like Walter said. They are the obvious builtin type for that.
cfg
and manipulate attributes through cfg.
qualifier..ini
and so on).Probably there are even more choices but I think the list looks enough for most tastes.
Now for the first question, that I think is a very good one, I am almost sure that the answer is no, you can't do that in Python. From here I found this which is the reasoning for self
use obligation. Safety, explicitness, and performance it looks. I suppose if it were to be allowed, you could use it too for self
, and maybe that's why you can't.
I sometimes miss that feature too.
Upvotes: 0
Reputation: 2169
You can easily do it using SimpleNamespace (Python3 only)
import types
obj = types.SimpleNamespace(
age=17
name="jack"
country="US"
...
weight=100
)
Upvotes: 1
Reputation: 12634
Why not
obj = {
'age': 17,
'name': 'jack',
'country': 'US',
...,
'weight': 100
}
? Newlines need no \
here, since they are inside a pair of braces.
Of course, this builds a dictionary, but do you really need an object of a specific class in a configuration?
Upvotes: 3