In search of python idiom for accessing arbitrary fields at run time

M

mshiltonj

I'm trying to find the preferred python idiom for access arbitrary
fields of objects at run time.


For example, say I have an object the business code will do
*something* with three arbitrary fields at a given time, but I don't
know what the three fields are at run time. In perl, I'd do something
like this:

sub three_fields{
my $self = shift;
my @fields = @_;

foreach my $field (@fields)
{
my $value = $self->$field; # this is the one I'm
interested in
[...]
}
}

In python, I'm doing something like this:

def three_fields(self, field1, field2, field3):
for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]

This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.

Thanks.
 
O

OKB (not okblacke)

mshiltonj said:
In python, I'm doing something like this:

def three_fields(self, field1, field2, field3):
for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]

This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.

I believe you are looking for the getattr function.

--
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is
no path, and leave a trail."
--author unknown
 
M

mshiltonj

mshiltonj said:
In python, I'm doing something like this:
def three_fields(self, field1, field2, field3):
for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]
This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.

I believe you are looking for the getattr function.

--
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is
no path, and leave a trail."
--author unknown


Doh. I figured it'd by FAQish. :-/ Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top