2

How can I get a list of which vars are defined in a class, without the classes imported in it?

vars(obj) returns all the vars in the class, excluding unwanted bliltin vars, like __doc__, __file__, __name__, __package__, os, pdb, etc.

Abhranil Das
  • 5,702
  • 6
  • 35
  • 42
iTayb
  • 12,373
  • 24
  • 81
  • 135
  • Could you maybe post a small example? – jamylak May 26 '12 at 14:18
  • 1
    Do you mean the variables defined in a class, or in a module? I would expect to see variables like `__file__` in the `vars()` for a module, but not for a class. Also, it's fairly unusual for a class to import modules, but common for a module to do so. (In Python, unlike Java, you typically don't put each class in its own module.) – Edward Loper May 26 '12 at 14:35
  • Yeah, I got mixed up with modules and classes. – iTayb May 26 '12 at 15:03

2 Answers2

1

You have several ways to get either the class variables or an instance variables. Leverage the coding conventions that enforce built-in functions being surrounded by double underscore chars ('__builtin__'):

class foo:
    baz = 51
    def __init__(self):
        self.bar = 42

>>> vars(foo)
{'__doc__': None,
 '__init__': <function __init__ at 0x02A35B70>,
 '__module__': '__main__',
 'baz': 51}
>>> {k:v for k,v in vars(foo).items() if k[:2]!="__" and k[-2:]!="__"}
{'baz': 51}
>>> obj = foo()
>>> vars(obj)
{'bar': 42}
Zeugma
  • 31,231
  • 9
  • 69
  • 81
0

Looking at the doc, I wonder if vars is what you want to use

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

I see this question on SO, that seem like what you want.

Let me know if I'm wrong

Community
  • 1
  • 1
jlengrand
  • 12,152
  • 14
  • 57
  • 87