[Tutor] new object attribute from string?

Gonšalo Rodrigues op73418@mail.telepac.pt
Sun Apr 13 19:07:09 2003

----- Original Message -----
From: "Chris Somerlot" <cdsomerl@murray-ky.net>
To: <tutor@python.org>
Sent: Sunday, April 13, 2003 11:33 PM
Subject: [Tutor] new object attribute from string?

> Is it possible to make a new object attribute or blank dictionary from
> the value of a string?
> IE I have a string 'dict' and I want dict = {} or object.dict

One way is

#Get dict class builtin by evaluating string.
cls = eval('dict')
#Call class.
obj = cls()

The builtin eval evaluates an *expression* in the current namespace and
returns the result. Since what we get is a class object (dict) we just call
it to get an instance of it - an empty dictionary.

But are you sure you want to do this? Calling pieces of code via strings (by
eval or exec) usually denotes Evil Programming, so if you tell us a little
more about what you are trying to accomplish maybe we can advise better ways
to do it. Usually, such needs of mapping strings to pieces of code are met
by Python dictionaries where the keys are the strings and the values
functions or callables. E.g. something like this

my_dict = {}
my_dict['dict'] = dict

And now you just do


You can even wrap the whole thing in syntax-sugar via classes. Something
like this should be enough (Python > 2.2)

class callable_dict(dict):
    def __call__(self, key, *args, **kwargs):
        return self[key](*args, **kwargs)

And now the above my_dict['dict']() is just


> Thanks
> Chris

All the best,
G. Rodrigues