Skip to content Skip to sidebar Skip to footer

How To Retrieve All Local Variables Of Another Module?

I am receiving a module as a parameter and I would like to retrieve all of it's local variables (nothing that relates to XXX or a function or a class). How can that be done? I ha

Solution 1:

You can access all of the local variables with dir(). This returns a list of strings, where each string is the name of the attribute. This returns all of the variables as well as the methods. If you are looking specifically for just the instance variables, these can be accessed through __dict__ for example:

>>> classFoo(object):
... def__init__(self, a, b, c):
>>>
>>> f = Foo(1,2,3)
>>> f.__dict__
{'a': 1, 'c': 3, 'b': 2}
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c']

Solution 2:

dir() returns a list of strings. Use setting.startswith() directly.

Post a Comment for "How To Retrieve All Local Variables Of Another Module?"