Sign in to follow this  
Lucidquiet

Python runtime access to method def attributes local variables

Recommended Posts

Suppose you have a module called Stuff.py and it has a method:
def myMod():
  """Attempting to assign attributes to local vars"""
  rv="void"
  ac=0
  nm="main"
  b="""
  blah
"""

How would I then access the variables rv, ac, nm, and b at runtime with introspection of the module and the method? L-

Share this post


Link to post
Share on other sites
Code objects are not containers for their variables. However, they do contain their symbols - i.e. variable names and constants.


>>> def myMod():
"""Attempting to assign attributes to local vars"""
rv="void"
ac=0
nm="main"
b="""
blah
"""

>>> dir(myMod.func_code)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts',
'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab',
'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> x = myMod.func_code
>>> x.co_names
('rv', 'ac', 'nm', 'b')
>>> x.co_varnames
('rv', 'b', 'ac', 'nm')
>>> x.co_consts
('Attempting to assign attributes to local vars', 'void', 0, 'main', '\n blah\n', None)
>>>


That's really as much as you can get out of it. After all, suppose one of those variables was *not* just assigned a constant: what would you like to have returned? Ok, the value of the variable within that function - but on which run of the function, and at what time? The whole concept is ill-defined.

On the other hand, if you just want to "decorate" function or code objects, just add to their attribute dicts:


myMod.extra_info = "this function rocks!"

# Zomg it's AOP tiem!!!11
results = [x() for x in globals().values() if callable(x)
and hasattr(x, 'extra_info') and '!' in x.extra_info]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this