How to succinctly list all attributes of classes and objects? - python

I have started to create classes and objects in python, progress is slow but I am getting there.
I wanted to ask the community whether it was possible to output all the attributes of a class/object.
I have created the following class:-
import inspect
class Helloclass:
def __init__(self):
self.A = ""
self.B = ""
self.C = ""
self.D = ""
london = Helloclass()
london.A = "Apples"
london.D = 120
print(inspect.getmembers(london))
I have created an object called london from Helloclass (so london is an instance of Helloclass).
There are 4 x properties that i coded into the class these are A, B, C, and D.
I have assigned the string 'Apples' to the A attribute of the london object.
I have assigned the value 120 to the A attribute of the london object.
I wanted to print out all of the available properties of the london object or the Helloclass class.
I have used the module inspect, however this gives me a horrible output and looks like:-
('A', 'Apples'), ('B', ''), ('C', ''), ('D', 120), ('__class__', <class '__main__.Helloclass'>),
('__delattr__', <method-wrapper '__delattr__' of Helloclass object at 0x000001E6B704CD00>),
('__dict__', {'A': 'Apples', 'B': '', 'C': '', 'D': 120}), ('__dir__', <built-in method __dir__ of
Helloclass object at 0x000001E6B704CD00>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of
Helloclass object at 0x000001E6B704CD00>), ('__format__', <built-in method __format__ of Helloclass
object at 0x000001E6B704CD00>), ('__ge__', <method-wrapper '__ge__' of Helloclass object at
0x000001E6B704CD00>), ('__getattribute__', <method-wrapper '__getattribute__' of Helloclass object at
0x000001E6B704CD00>), ('__gt__', <method-wrapper '__gt__' of Helloclass object at
0x000001E6B704CD00>), ('__hash__', <method-wrapper '__hash__' of Helloclass object at
0x000001E6B704CD00>), ('__init__', <bound method Helloclass.__init__ of <__main__.Helloclass object
at 0x000001E6B704CD00>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at
0x000001E6B57CF350>), ('__le__', <method-wrapper '__le__' of Helloclass object at
0x000001E6B704CD00>), ('__lt__', <method-wrapper '__lt__' of Helloclass object at
0x000001E6B704CD00>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of Helloclass
object at 0x000001E6B704CD00>), ('__new__', <built-in method __new__ of type object at
0x00007FFF9F7DCB50>), ('__reduce__', <built-in method __reduce__ of Helloclass object at
0x000001E6B704CD00>), ('__reduce_ex__', <built-in method __reduce_ex__ of Helloclass object at
0x000001E6B704CD00>), ('__repr__', <method-wrapper '__repr__' of Helloclass object at
0x000001E6B704CD00>), ('__setattr__', <method-wrapper '__setattr__' of Helloclass object at
0x000001E6B704CD00>), ('__sizeof__', <built-in method __sizeof__ of Helloclass object at
0x000001E6B704CD00>), ('__str__', <method-wrapper '__str__' of Helloclass object at
0x000001E6B704CD00>), ('__subclasshook__', <built-in method __subclasshook__ of type object at
0x000001E6B57CF350>), ('__weakref__', None)
Although this gives me what i want, there is so much extra stuff which I do not need or want to see.
I just want the output to be something like:-
london Object of Class Helloclass
london.A = "Apples"
london.B = ""
london.C = ""
london.D = 120
Is there any way of getting cleaner output?

You could simply do this to get both.
import inspect
class Helloclass:
def __init__(self):
self.A = ""
self.B = ""
self.C = ""
self.D = ""
def __str__(self):
return str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
london = Helloclass()
london.A = "Apples"
london.D = 120
print(london)
Should produce something close
<class '__main__.Helloclass'>
A = Apples
B =
C =
D = 120
You could also use self.class.name and change up the string however you want.
def __str__(self):
return 'Object of Class '+str(self.__class__.__name__ ) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
It should be closer.
Object of Class Helloclass
A = Apples
B =
C =
D = 120

You could use vars to get this kind of output
>>> vars(london)
{'A': 'Apples', 'B': '', 'C': '', 'D': 120}

Related

display class variable values in python

I have a class in python (eg)
testclass()
this class has some internal (private variables) which are assigned values within functions of the class.
(eg)
class wrapperfunction():
def testfunc():
self.__testvalue = 123
Is there a way i can view this variable's value from outside the class in another notebook
all code is written in Databricks and one notebook calls this class.
the notebook code is as under
%run ../Testnotebook/
wrapperfunction('testing')
Being fairly new to python i cant figure out how to view the value of a class function inside another function as shown above, in my main notebook.
I have tried the following to get all the variables, but this below code doesn't give me the value of the variable at runtime.
my_obj = testclass()
attribs = vars(my_obj)
I need to output / view the values at runtime to debug my code.
Actually, here is no private methods and attributes in python.
Any information can be visible outside class.
So, starting private variable names from __ is just a convention like Please don't touch this private variable because I may change it in future without thinking about compatibility.
dir function allow to get all class's attribute names:
class A:
__private_var = None
def __init__(self):
self.__private_var = 123
a = A()
for attr_name in dir(a):
try:
print(attr_name, ':', getattr(a, attr_name, 'non printable'))
except:
print(f'Could not print value of {attr_name}')
And output will be:
_A__private_var : 123
__class__ : <class '__main__.A'>
__delattr__ : <method-wrapper '__delattr__' of A object at 0x7fc196577fd0>
__dict__ : {'_A__private_var': 123}
__dir__ : <built-in method __dir__ of A object at 0x7fc196577fd0>
__doc__ : None
__eq__ : <method-wrapper '__eq__' of A object at 0x7fc196577fd0>
__format__ : <built-in method __format__ of A object at 0x7fc196577fd0>
__ge__ : <method-wrapper '__ge__' of A object at 0x7fc196577fd0>
__getattribute__ : <method-wrapper '__getattribute__' of A object at 0x7fc196577fd0>
__gt__ : <method-wrapper '__gt__' of A object at 0x7fc196577fd0>
__hash__ : <method-wrapper '__hash__' of A object at 0x7fc196577fd0>
__init__ : <bound method A.__init__ of <__main__.A object at 0x7fc196577fd0>>
__init_subclass__ : <built-in method __init_subclass__ of type object at 0x55877920c400>
__le__ : <method-wrapper '__le__' of A object at 0x7fc196577fd0>
__lt__ : <method-wrapper '__lt__' of A object at 0x7fc196577fd0>
__module__ : __main__
__ne__ : <method-wrapper '__ne__' of A object at 0x7fc196577fd0>
__new__ : <built-in method __new__ of type object at 0x5587774d5de0>
__reduce__ : <built-in method __reduce__ of A object at 0x7fc196577fd0>
__reduce_ex__ : <built-in method __reduce_ex__ of A object at 0x7fc196577fd0>
__repr__ : <method-wrapper '__repr__' of A object at 0x7fc196577fd0>
__setattr__ : <method-wrapper '__setattr__' of A object at 0x7fc196577fd0>
__sizeof__ : <built-in method __sizeof__ of A object at 0x7fc196577fd0>
__str__ : <method-wrapper '__str__' of A object at 0x7fc196577fd0>
__subclasshook__ : <built-in method __subclasshook__ of type object at 0x55877920c400>
__weakref__ : None
Where _A__private_var is what are you looking for
Also a.__dict__.get('_A__private_var', None) may be used (as you can see at output above)
If method or attribute is private, python changes it name as _{CLASS_NAME}__{ATTR_NAME} (this is a new behavior I didn't know before 0_o). So if private attribute name is known you may use construction like:
priv_attr_name = '__private_var'
# Where `a` is created inside example above
# value is `123`
value = getattr(a, f'_{a.__class__.__name__}{priv_attr_name}', None)
# Same as above: value is `123`
value = a.__dict__.get(f'_{a.__class__.__name__}{priv_attr_name}', None)
Notice: a.__dict__ is only acceptable if you set an attribute after instantiating. a.__dict__ don't show class attibutes and only shows attributes of instance:
class B:
__priv_a = 123
__priv_b = None
__priv_c = None
def __init__(self):
self.__priv_b = 456
def set_c(self):
self.__priv_c = 789
b = B()
b.set_c()
print('__priv_a', b.__dict__.get(f'_{b.__class__.__name__}__priv_a', 'not found'))
print('__priv_b', b.__dict__.get(f'_{b.__class__.__name__}__priv_b', 'not found'))
print('__priv_c', b.__dict__.get(f'_{b.__class__.__name__}__priv_c', 'not found'))
And output will be:
__priv_a not found
__priv_b 456
__priv_c 789

Nicely print "public" methods of python class

I am trying to design an API in python using a class:
class SimulationApi(object):
def hello(self):
return "Hi"
def echo(self, string):
return string
def get_foo(self):
return self.foo
def __init__(self):
self.foo = 50
And i'd like to print to console a list of available public methods defined by the class. Is there a way to to this automatically, that will also pick up the method parameters? Ideally, the output would look like this:
SimulationApi:
get_foo()
echo(string)
hello()
So far, my solution is this, but it is not complete and may be the wrong direction.
print("SimulationApi: \n\t{}\n".format("\n\t".join([x+"()" for x in dir(SimulationApi) if not x.startswith("__")]))
You can use inspect module:
class SimulationApi(object):
def hello(self):
return "Hi"
def echo(self, string):
return string
def get_foo(self):
return self.foo
def __init__(self):
self.foo = 50
import inspect
inspect.getmembers(SimulationApi)
Will return:
[('__class__', type),
('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
('__dict__',
mappingproxy({'__module__': '__main__',
'hello': <function __main__.SimulationApi.hello(self)>,
'echo': <function __main__.SimulationApi.echo(self, string)>,
'get_foo': <function __main__.SimulationApi.get_foo(self)>,
'__init__': <function __main__.SimulationApi.__init__(self)>,
'__dict__': <attribute '__dict__' of 'SimulationApi' objects>,
'__weakref__': <attribute '__weakref__' of 'SimulationApi' objects>,
'__doc__': None})),
('__dir__', <method '__dir__' of 'object' objects>),
('__doc__', None),
('__eq__', <slot wrapper '__eq__' of 'object' objects>),
('__format__', <method '__format__' of 'object' objects>),
('__ge__', <slot wrapper '__ge__' of 'object' objects>),
('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),
('__gt__', <slot wrapper '__gt__' of 'object' objects>),
('__hash__', <slot wrapper '__hash__' of 'object' objects>),
('__init__', <function __main__.SimulationApi.__init__(self)>),
('__init_subclass__', <function SimulationApi.__init_subclass__>),
('__le__', <slot wrapper '__le__' of 'object' objects>),
('__lt__', <slot wrapper '__lt__' of 'object' objects>),
('__module__', '__main__'),
('__ne__', <slot wrapper '__ne__' of 'object' objects>),
('__new__', <function object.__new__(*args, **kwargs)>),
('__reduce__', <method '__reduce__' of 'object' objects>),
('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
('__repr__', <slot wrapper '__repr__' of 'object' objects>),
('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
('__sizeof__', <method '__sizeof__' of 'object' objects>),
('__str__', <slot wrapper '__str__' of 'object' objects>),
('__subclasshook__', <function SimulationApi.__subclasshook__>),
('__weakref__', <attribute '__weakref__' of 'SimulationApi' objects>),
('echo', <function __main__.SimulationApi.echo(self, string)>),
('get_foo', <function __main__.SimulationApi.get_foo(self)>),
('hello', <function __main__.SimulationApi.hello(self)>)]
Note: Your methods (the methods you like to get info) are also the SimulationApi class dictionary __dict__.
You can get the full code for your echo function like this:
import inspect
lines = inspect.getsource(SimulationApi.echo)
print(lines)
def echo(self, string):
return string

How to get instance attribute name-values in a class with __slots__ in Python

When defining two classes, one with the __dict__ implementation (A) and the other with __slots__ implementation (B).
Is there a clever way of getting the instance attribute names and values of the __slots__ class, as I would with using the vars() function on the __dict__ class?
class A(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class B(object):
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
vars(A(1, 2, 3)) # {'y': 2, 'x': 1, 'z': 3}
vars(B(1, 2, 3)) # TypeError: vars() argument must have __dict__ attribute
using .__slots__ or dir() with inspection would just return the attribute names, without the value
B(1, 2, 3).__slots__ # ('x', 'y', 'z')
Here's a function I've used before:
def vars2(obj):
try:
return vars(obj)
except TypeError:
return {k: getattr(obj, k) for k in obj.__slots__}
In [2]: x = B(1,2,3)
In [3]: {a: x.__getattribute__(a) for a in dir(x)}
Out[3]:
{'__class__': __main__.B,
'__delattr__': <method-wrapper '__delattr__' of B object at 0x7f3bb2b48e18>,
'__doc__': None,
'__format__': <function __format__>,
'__getattribute__': <method-wrapper '__getattribute__' of B object at 0x7f3bb2b48e18>,
'__hash__': <method-wrapper '__hash__' of B object at 0x7f3bb2b48e18>,
'__init__': <bound method B.__init__ of <__main__.B object at 0x7f3bb2b48e18>>,
'__module__': '__main__',
'__new__': <function __new__>,
'__reduce__': <function __reduce__>,
'__reduce_ex__': <function __reduce_ex__>,
'__repr__': <method-wrapper '__repr__' of B object at 0x7f3bb2b48e18>,
'__setattr__': <method-wrapper '__setattr__' of B object at 0x7f3bb2b48e18>,
'__sizeof__': <function __sizeof__>,
'__slots__': ('x', 'y', 'z'),
'__str__': <method-wrapper '__str__' of B object at 0x7f3bb2b48e18>,
'__subclasshook__': <function __subclasshook__>,
'x': 1,
'y': 2,
'z': 3}
Or if you don't want to see magic methods:
In [4]: {a: x.__getattribute__(a) for a in dir(x) if not a.startswith('__')}
Out[4]: {'x': 1, 'y': 2, 'z': 3}

Inspecting Python Objects

I am looking at a code given to me by a co-worker who no longer works with us.
I have a list variable called rx.
>> type(rx)
type 'list'
When I go to look inside rx[0] I get this:
>> rx[0]
<Thing.thing.stuff.Rx object at 0x10e1e1c10>
Can anyone translate what this means? And, more importantly, how can I see what is inside this object within the rx list?
Any help is appreciated.
Start with help: help(rx[0])
# example python object
class Employee:
"""Common base class for all employees."""
empCount = 0
help(Employee)
Output:
Help on class Employee in module __main__:
class Employee(builtins.object)
| Common base class for all employees.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| empCount = 0
If that's not enough info check out the inspect module.
Inspect has a lot of methods that might be useful, like getmembers and getdoc:
import inspect
inspect.getdoc(Employee) # 'Common base class for all employees.'
for name, data in inspect.getmembers(Employee):
if name == '__builtins__':
continue
print('%s :' % name, repr(data))
Output:
__class__ : <class 'type'>
__delattr__ : <slot wrapper '__delattr__' of 'object' objects>
__dict__ : mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, 'empCount': 0, '__doc__': 'Common base class for all employees.'})
__dir__ : <method '__dir__' of 'object' objects>
__doc__ : 'Common base class for all employees.'
__eq__ : <slot wrapper '__eq__' of 'object' objects>
__format__ : <method '__format__' of 'object' objects>
__ge__ : <slot wrapper '__ge__' of 'object' objects>
__getattribute__ : <slot wrapper '__getattribute__' of 'object' objects>
__gt__ : <slot wrapper '__gt__' of 'object' objects>
__hash__ : <slot wrapper '__hash__' of 'object' objects>
__init__ : <slot wrapper '__init__' of 'object' objects>
__le__ : <slot wrapper '__le__' of 'object' objects>
__lt__ : <slot wrapper '__lt__' of 'object' objects>
__module__ : '__main__'
__ne__ : <slot wrapper '__ne__' of 'object' objects>
__new__ : <built-in method __new__ of type object at 0x108a69d20>
__reduce__ : <method '__reduce__' of 'object' objects>
__reduce_ex__ : <method '__reduce_ex__' of 'object' objects>
__repr__ : <slot wrapper '__repr__' of 'object' objects>
__setattr__ : <slot wrapper '__setattr__' of 'object' objects>
__sizeof__ : <method '__sizeof__' of 'object' objects>
__str__ : <slot wrapper '__str__' of 'object' objects>
__subclasshook__ : <built-in method __subclasshook__ of type object at 0x7faa994086e8>
__weakref__ : <attribute '__weakref__' of 'Employee' objects>
empCount : 0

Finding out which functions are available from a class instance in python?

How do you dynamically find out which functions have been defined from an instance of a class?
For example:
class A(object):
def methodA(self, intA=1):
pass
def methodB(self, strB):
pass
a = A()
Ideally I want to find out that the instance 'a' has methodA and methodB, and which arguments they take?
Have a look at the inspect module.
>>> import inspect
>>> inspect.getmembers(a)
[('__class__', <class '__main__.A'>),
('__delattr__', <method-wrapper '__delattr__' of A object at 0xb77d48ac>),
('__dict__', {}),
('__doc__', None),
('__getattribute__',
<method-wrapper '__getattribute__' of A object at 0xb77d48ac>),
('__hash__', <method-wrapper '__hash__' of A object at 0xb77d48ac>),
('__init__', <method-wrapper '__init__' of A object at 0xb77d48ac>),
('__module__', '__main__'),
('__new__', <built-in method __new__ of type object at 0x8146220>),
('__reduce__', <built-in method __reduce__ of A object at 0xb77d48ac>),
('__reduce_ex__', <built-in method __reduce_ex__ of A object at 0xb77d48ac>),
('__repr__', <method-wrapper '__repr__' of A object at 0xb77d48ac>),
('__setattr__', <method-wrapper '__setattr__' of A object at 0xb77d48ac>),
('__str__', <method-wrapper '__str__' of A object at 0xb77d48ac>),
('__weakref__', None),
('methodA', <bound method A.methodA of <__main__.A object at 0xb77d48ac>>),
('methodB', <bound method A.methodB of <__main__.A object at 0xb77d48ac>>)]
>>> inspect.getargspec(a.methodA)
(['self', 'intA'], None, None, (1,))
>>> inspect.getargspec(getattr(a, 'methodA'))
(['self', 'intA'], None, None, (1,))
>>> print inspect.getargspec.__doc__
Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
>>> print inspect.getmembers.__doc__
Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate.

Categories