Finding out which functions are available from a class instance in python? - 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.

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

How to succinctly list all attributes of classes and objects?

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}

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

When is type(instance) different from instance.__class__?

Python has the built-in function type:
class type(object)
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
Python also has the special attribute __class__:
instance.__class__
The class to which a class instance belongs.
I used to believe that they both refer to the same object. However in the method abc.ABCMeta.__instancecheck__ there is a check if they are identical:
def __instancecheck__(cls, instance):
"""Override for isinstance(instance, cls)."""
# Inline the cache checking
subclass = instance.__class__
# […]
subtype = type(instance)
if subtype is subclass:
# […]
When is type(instance) different from instance.__class__?
type(instance) and instance.__class__ may be different, even with new-style classes, as Guido van Rossum mentioned in PEP 3119:
Also, isinstance(x, B) is equivalent to issubclass(x.__class__, B) or issubclass(type(x), B). (It is possible type(x) and x.__class__ are not the same object, e.g. when x is a proxy object.)
For example, the function weakref.proxy of the standard library creates proxy objects.
>>> import weakref
>>> class A: pass
...
>>> a = A()
>>> type(weakref.proxy(a))
<class 'weakproxy'>
>>> weakref.proxy(a).__class__
<class '__main__.A'>
>>> repr(weakref.proxy(a))
'<weakproxy at 0x10065ab30 to A at 0x1006534c0>'
Note that the implementation of the __repr__ method of the proxy object uses type(instance), not instance.__class__, since the primary purpose the __repr__ method is to provide enough information to recreate the object when debugging.
type(instance)
The real class of an object instance is stored on the instance in a __class__ slot (i.e. at a fixed offset in the instance layout). It can only be accessed through the data descriptor vars(object)['__class__'] (whose method __get__ allows attribute retrieval, whose method __set__ allows attribute assignment, and whose method __delete__ forbids attribute deletion), or equivalently through the built-in function type (whose one-argument form allows attribute retrieval):
>>> class A: pass
...
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> vars(object)['__class__'].__get__(a)
<class '__main__.A'>
>>> class B: pass
...
>>> vars(object)['__class__'].__set__(a, B)
>>> type(a)
<class '__main__.B'>
>>> vars(object)['__class__'].__get__(a)
<class '__main__.B'>
>>> vars(object)['__class__'].__delete__(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't delete __class__ attribute
instance.__class__
If the data descriptor vars(object)['__class__'] is not overridden in an object subclass, instance.__class__ accesses the real class of instance through the data descriptor:
>>> class A: pass
...
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> a.__class__
<class '__main__.A'>
>>> class B: pass
...
>>> a.__class__ = B
>>> type(a)
<class '__main__.B'>
>>> a.__class__
<class '__main__.B'>
>>> del a.__class__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't delete __class__ attribute
But if the data descriptor vars(object)['__class__'] is overridden in an object subclass, instance.__class__ does not access the real class of instance. Moreover, if the override is not a data descriptor, it can itself be overridden in instance:
>>> class A: __class__ = int # overrides vars(object)['__class__']
...
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> a.__class__
<class 'int'>
>>> a.__class__ = str # overrides vars(A)['__class__'] (not a data descriptor)
>>> type(a)
<class '__main__.A'>
>>> a.__class__
<class 'str'>
>>> del a.__class__
>>> type(a)
<class '__main__.A'>
>>> a.__class__
<class 'int'>
This is the case for old style objects (inheriting from nothing). Such objects do not have the __class__ property. I think they do it this way to prevent errors. Example for Python 2.7:
class A:
pass
class B(object):
pass
a = A()
b = B()
print(dir(a)) # ['__doc__', '__module__']
print(dir(b)) # ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
print(b.__class__) # <class '__main__.B'>
print(type(b)) # <class '__main__.B'>
#####################
# The intersting part
print(a.__class__) # __main__.A
print(type(a)) # <type 'instance'>
print(B.__class__) # <type 'type'>
print(type(B)) # <type 'type'>
print(type(A)) # <type 'classobj'>
#print(A.__class__) # AttributeError: class A has no attribute '__class__'
See this for further information:
Python type() or __class__, == or is
NewClassVsClassicClass
Why does `type(myField)` return `<type 'instance'>` and not `<type 'Field'>`?
Note: The given lines from cpython were changed in 2008 last time (commit), so it really seems to be a compatibility thing or they just forgot about it.

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

Categories