Jump to content
  • Advertisement
Sign in to follow this  
Lucidquiet

Python runtime access to method def attributes local variables

This topic is 4496 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!