using getattr/setattr for local variables in a member function

Ned Batchelder ned at nedbatchelder.com
Fri Nov 22 02:58:38 CET 2013


On Thursday, November 21, 2013 6:12:10 PM UTC-5, Catherine M Moroney wrote:
> Hello,
> 
> If I have a class that has some member functions, and all the functions 
> define a local variable of the same name (but different type), is there
> some way to use getattr/setattr to access the local variables specific 
> to a given function?
> 
> Obviously there's no need to do this for the small test case below,
> but I'm working on a bigger code where being able to loop through
> variables that are local to func2 would come in handy.
> 
> For example:
> 
> class A(object):
>     def __init__(self):
> 	pass
> 
>     def func1(self):
> 	a = {"A": 1}
> 	b = {"B": 2}
> 
>     def func2(self):
>       a = [1]
> 	b = [2]
> 
> 	for attr in ("a", "b"):
> 	   var = getattr(self, attr)  ! What do I put in place of self
> 	   var.append(100)            ! to access vars "a" and "b" that
>                                     ! are local to this function?
> 
> Catherine

Catherine, it's a little hard to know what your real code is doing from this toy sample.  Usually, if you want to work with "variable variables" as you're suggesting here, the better approach is to use one dictionary instead of many variables.  Then you can deal with them as a single collection much more conveniently.

Can you show us the real code in question?  It will be much easier to make a good recommendation if we can see what you are doing with these variables.

--Ned.



More information about the Python-list mailing list