display class variable values in python - 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

Related

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}

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

Can __setattr__() can be defined in a class with __slots__?

Say I have a class which defines __slots__:
class Foo(object):
__slots__ = ['x']
def __init__(self, x=1):
self.x = x
# will the following work?
def __setattr__(self, key, value):
if key == 'x':
object.__setattr__(self, name, -value) # Haha - let's set to minus x
Can I define __setattr__() for it?
Since Foo has no __dict__, what will it update?
All your code does, apart from negate the value, is call the parent class __setattr__, which is exactly what would happen without your __setattr__ method. So the short answer is: Sure you can define a __setattr__.
What you cannot do is redefine __setattr__ to use self.__dict__, because instances of a class with slots do not have a __dict__ attribute. But such instances do have a self.x attribute, it's contents are just not stored in a dictionary on the instance.
Instead, slot values are stored in the same location a __dict__ instance dictionary would otherwise be stored; on the object heap. Space is reserved for len(__slots__) references, and descriptors on the class access these references on your behalf.
So, in a __setattr__ hook, you can just call those descriptors directly instead:
def __setattr__(self, key, value):
if key == 'x':
Foo.__dict__[key].__set__(self, -value)
Interesting detour: yes, on classes without a __slots__ attribute, there is a descriptor that would give you access to the __dict__ object of instances:
>>> class Bar(object): pass
...
>>> Bar.__dict__['__dict__']
<attribute '__dict__' of 'Bar' objects>
>>> Bar.__dict__['__dict__'].__get__(Bar(), Bar)
{}
which is how normal instances can look up self.__dict__. Which makes you wonder where the Bar.__dict__ object is found. In Python, it is turtles all the way down, you'd look that object up on the type object of course:
>>> type.__dict__['__dict__']
<attribute '__dict__' of 'type' objects>
>>> type.__dict__['__dict__'].__get__(Bar, type)
dict_proxy({'__dict__': <attribute '__dict__' of 'Bar' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None})

Why __get__ method is not called for instance attribute?

There is this code:
class A:
def __init__(self, x):
self.x = x
def __get__(self, obj, type=None):
print("__get__")
return self.x
def __set__(self, obj, value):
pass
class B:
a_oc = A(44)
def __init__(self, y):
self.a_ob = A(y)
b = B(3)
print(b.a_oc) # class attribute called __get__
print(b.a_ob) # __get__ not called
For class attribute __get__ is called, for instance attribute it is not. Why?
The attribute lookup rule for the new type class(class in 3.x and class inherits from object in 2.x) is, take obj.attr:
if the value is generated by Python, such as __hash__, return it
lookup in obj.__class__.__dict__, if it exists and there exists __get__, return the result of attr.__get__(obj, obj.__class__), if not, lookup in the parent class recursively.
lookup in obj.__dict__. If obj is an instance and the attr exists, return it, or next step. Else if the obj is a class, lookup in itself's, its parents' __dict__, if it is a descriptor, return attr.__get__(None, obj.__class__) or the attr itself.
lookup in obj.__class__.__dict__. If attr is a non-data descriptor, return the result of it. Else return the attr itself if it exists.
raise AttributeError
See you class:
>>> b.__class__
<class 'des.B'>
>>> b.__class__.__dict__
mappingproxy({'__init__': <function B.__init__ at 0x7f2dacb4e290>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'B' objects>, '__dict__': <attribute '__dict__' of 'B' objects>, 'a_oc': <des.A object at 0x7f2dacb5de50>, '__module__': 'des', '__qualname__': 'B'})
>>>
>>> b.__dict__
{'a_ob': <des.A object at 0x7f2dacb5df10>}
>>>
b.a_oc fits step 2 and b.a_ob fits step3. I put your code in module des.

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