access method local variable namespace?

Quinn Dunkan quinn at bolivar.ugcs.caltech.edu
Thu May 11 18:54:57 CEST 2000


On Thu, 11 May 2000 07:13:19 -0700, emile at fenx.com <emile at fenx.com> wrote:
>Accessing an instances' values is rather easy, but if I get your
>meaning, you want to access, eg, local_var from the __init__ 
>method in the sample code below?  I don't know how you'd get
>to it without saving a reference to it somewhere.  Maybe
>someone can point out a way if I'm wrong.  Of course, the
>easy way would be to make it an instance variable.
...
>Douglas du Boulay <ddb at crystal.uwa.edu.au> wrote in message
>news:<391A3F65.54AC9105 at crystal.uwa.edu.au>...
>> hi,
>> 
>> I know it's possible to access the names of methods within 
>> class objects from their __class__.__dict__, but I am 
>> wondering if it's also possible to 
>> access the namespace of the local variables in those 
>> methods and to read their contents?
>> 
>> >From the "Programming Python" book I read that local variables are
>> stored in an array instead of a dictionary for faster access and that
>> vars() and locals() can be used to access those variables when 
>> they are in the current scope, but is it possible to this when they
>> are out of scope?

Well, generally the whole point of local variables are that you don't mess
with them outside of scope.  You're doing a lot of work to defeat the whole
purpuose, why not just use globals while you're at it?

def f(x):
    y = x * 2
    print x

What should I get if I ask for the local 'y' variable of the 'f' function?
However, you can get local *constants*:

>>> def f(x):
...   y = 'constant'
...   print x
... 
>>> f.func_code.co_consts
(None, 'constant')
>>> # the first one is always the docstring

Unless you're entering an obfuscated code contest, I'm not sure how this is
helpful, but there ya go :)

python:-more-than-enough-rope-ly y'rs



More information about the Python-list mailing list