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.
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.
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}
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