[Tutor] Exec(uting) Code in a Dictionary?

spir denis.spir at free.fr
Sun Feb 8 09:56:03 CET 2009


Le Sat, 07 Feb 2009 13:50:01 -0800,
Wayne Watson <sierra_mtnview at sbcglobal.net> a écrit :

> That's something for me to ponder, setattr. I'd rather not go off and pick up on something like ConfigParser at this stage. I'd like to keep this code somewhat simple and easy to understand, but yet have some flexibility for changes.

Dicts are very handy because they are still starightforwardly usable when a name/key is unknown at design time, in addition to the value:

d["foo"] = val
d[name] = val

A typical use is precisely reading data from a config file where both names and values are data, meaning defined by the user. So that you cannot directly store them in a custom config object writing:

config.name = val

Setattr addresses this need:

setattr(config,name,val)

So that finally using an object or a dict are more or less equivalent, rather a programmer choice.
* dict is slightly easier
* object allows slightly lighter code (obj.name vs obj["name"]) and a syntax better consistent with the rest of python
* additionnal data attibutes, custom behaviour

Denis


------
la vida e estranya


More information about the Tutor mailing list