Checking a variable (object) by printing it

In Ruby, you can test a variable (object) for p my_objthat it prints it as "deep" and as detailed as possible. This is useful for logging and debugging. In python, I thought it was print my_obj, only it did not print much, but <requests.sessions.Session object at 0x7febcb29b390>that was not useful at all.

How to do it?

+4
source share
5 answers

You can use the varsbuilt-in method to get the attribute dictionary of an object:

>>> import requests
>>> r = requests.Session()
>>> vars(r)
{'cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>, 'stream': False, 'hooks': {'response': []}, 'auth': None, 'trust_env': True, ...}

Perhaps connect it with pprintto get a formatted result:

>>> import pprint
>>> pprint.pprint(vars(r), indent=2)
{ 'adapters': OrderedDict([('https://', <requests.adapters.HTTPAdapter object at 0x103106690>), ('http://', <requests.adapters.HTTPAdapter object at 0x103106790>)]),
  'auth': None,
  'cert': None,
  'cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>,
  ...
+3
source

"" , ; , .

, - , , , - . . , , ; , , .

, __str__(), . , print obj, object __str__(), .

, request.Session() my_obj, print(my_obj.text) .

http://docs.python-requests.org/en/latest/user/advanced/

+2

dir(), , , :

for key in dir(my_obj):
    print('{}: {}'.format(key, getattr(my_obj, key))

, , :)

+2

inspect:

import inspect
print inspect.getmembers(my_obj)

__dict__, , .

+2

, __repr__ __str__ .

class Node(object):
    """ A node object with an index"""
    def __init__(self,index = 0):
        self.index = index

    def __repr__(self):
        print "Node %s" % self.index

    def __str__(self):
        print "Node %s" % self.index

, , , __str__ .

: __str__ __repr__ Python

-1

Source: https://habr.com/ru/post/1548387/


All Articles