naming objects from string
Wildemar Wildenburger
wildemar at freakmail.de
Thu Sep 21 00:50:44 EDT 2006
manstey wrote:
> If I have a string, how can I give that string name to a python object,
> such as a tuple.
>
> e.g.
>
> a = 'hello'
> b=(1234)
>
> and then a function
> name(b) = a
>
> which would mean:
> hello=(1234)
>
> is this possible?
>
Direct answer:
Look up the setattr() functions (DO look it up!). Replace your
name(b) = a line with
setattr(__builtins__, a, b).
There you go.
Hopefully more helpful answer:
One alternative would be using a dictionary. Your example would then
translate to:
a = 'hello'
b = (1234,) # notice the comma!
# without it, it wouldn't be a tuple but a simple
# parenthesized integer
d = {} # your dictionary
d[a] = b # assign the value of b to a key given by a
d[a]
>>> (1234,)
d['hello']
>>> (1234,)
In most cases this will be a LOT less cumbersome compared to messing
with module attributes.
hope that helps a bit
wildemar
More information about the Python-list
mailing list