[Q/newbie] Converting object names to strings and back?

Alex Martelli aleax at aleax.it
Tue Aug 21 09:59:00 CEST 2001

"Adam Twardoch" <list.adam at twardoch.com> wrote in message
news:to3pa38u7j4690 at news.supernews.com...
> My question: how can I determine the name of a particular object, or,
> precisely, convert it to a string?

In general, you can't.  The Python FAQ's explain it well, e.g. at:
(I suggest reading the FAQ's could be very instructive).

> And then, when I have a string (for
> example "MyObject.property"), how can I make Python find the object with
> that particular name?

That's easy (although unlikely to be what you should really be
doing) -- eval(thestring) will evaluate any expression to which
string variable thestring refers, and a name is just a special
case of expression.  Your example is not a name, by the way: it
is the application of the attribute-access operation to an
object (of which you do indeed supply just the name) and an
attributename -- if you used a solution that does indeed only
work for names, it would fail for your example, but eval, which
does completely unrestricted expression, would work.

Of course, it's horribly dangerous to evaluate just any expression
unless you're *REALLY* sure about where it's coming from -- which
is part of why it's quite unlikely that this is what you should
really be doing.

> I know that in Perl, constructs like $$variable can help.

It's rightfully forbidden when you use Perl in the recommended
way (use strict), if I recall correctly.  Not quite as
dangerous as eval, but still quite iffy, and a horrid
programming practice.  Python doesn't have a mode in which
you're forbidden horrid programming practices (it does have
a restricted-execution mode where you can forbid untrusted
code from doing damage, but the untrusted code can still be
written horrendously:-): Python gives you all the tools you
need to program well, and it's then up to you to use them.

> I'm just starting with Python, so please have mercy. And, I must use Py
> 1.5.2 for Windows.

That's a pity (not the Windows part, as Python runs just as
well on Windows as on Unix-like systems -- the 1.5.2 part,
which means you're forced to use a release that's years
old when solid, faster, bright 2.1.1 has been out for
quite a while...!).  But it doesn't affect the specific
tasks you're asking about in this post.


More information about the Python-list mailing list