I want to do dynamic access to member variables in Python - reading from
and writing to object member variables based on a member name stored in
a string. If the member is stored in __dict__ it is easy enough, but
what if it is emulated with __getattr__, or a property, or __getattribute__?

exec() gives the same behavior, but can cause bad performance if you do
it a lot, because it has to compile the code. Is there any way to get
Python to do exactly the same thing as x.y = a and a = x.y, when the
member name is a string.

The following functions work well enough for normal member variables -
is there a canonical way of doing this in the generic case?

def GetMemberVariable(object, attributeName):
return object.__dict__[attributeName]

def SetMemberVariable(object, attributeName, newValue):
object.__dict__[attributeName] = newValue

# Sample usage:
a = GetMemberVariable(x, "y")
SetMemberVariable(x, "y", 0)

Thanks for any help.

Bruce Dawson

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 4 | next ›
Discussion Overview
grouppython-list @
postedOct 17, '02 at 5:31a
activeOct 18, '02 at 4:51a



site design / logo © 2022 Grokbase