[Q/newbie] Converting object names to strings and back?
Richard Jones
richard at bizarsoftware.com.au
Tue Aug 21 01:08:07 EDT 2001
On Tuesday 21 August 2001 14:32, Adam Twardoch wrote:
> I'm trying to write the contents of some Python objects to a text file. The
> output should look like
> objectname + "=" + objectcontents
> objectname + "=" + objectcontents
>
> Then, I want to read that file and store the objectcontents in the
> respective objects.
Note that unless you're doing this for reasons of radability or editability,
Python already has facilities for dumping and reading objects to and from
files. Look up pickle and marshal in the standard library reference.
> My question: how can I determine the name of a particular object, or,
> precisely, convert it to a string? And then, when I have a string (for
> example "MyObject.property"), how can I make Python find the object with
> that particular name?
>
> I know that in Perl, constructs like $$variable can help.
First up, you need to know what namespace you're working in. Python's name
lookup works through two namespaces to find things: locals and then globals.
To emulate the perl, you're going to have to do both. Also, if your string
has attribute accesses like your example above, you'll want to split it up to
walk the names correctly.
object, attribute = "MyObject.property".split('.')
global_d, local_d = globals(), locals()
if global_d.has_key(object):
object = global_d[object]
else:
object = local_d[object]
attribute = getattr(object, attribute)
>From my memory of Perl, the closest to a direct translation of the perl code
is:
attribtue = eval("MyObject.property")
... but eval should be considered dangerous (as should $$variable I think) if
the source of the string is not "trusted". The first solution is far safer,
using explicit introspection techniques.
Richard
More information about the Python-list
mailing list