weiweishuo
weiweishuo

Reputation: 927

Does python has something similar to _ENV in lua?

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

Answers (3)

progmatico
progmatico

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.

  • make your own Configuration class, instantiate cfgand manipulate attributes through cfg. qualifier.
  • use a shelf, a persistant dict with the shelve module.
  • Because shelves use pickle and this is a binary format used mostly in Python (I think)to store objects, you may prefer to use some more human oriented open format like suggested by DeepSpace and Cartucho (see configparser for .iniand so on).
  • Much like with the class case, use a namedtuple or a SimpleNamespace (didn't know this one) like Wouda and luminousmen said.

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

luminousmen
luminousmen

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

Walter Tross
Walter Tross

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

Related Questions