7

In Ruby one can inspect a variable (object) by p my_obj so it'll print it as "deep" and in detail as possible. It's useful for logging and debugging. In python I thought it was print my_obj, only it didn't print much but <requests.sessions.Session object at 0x7febcb29b390> which wasn't useful at all.

How do I do this?

5 Answers5

5

dir() will probably give you what you want:

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

There's a lot more information there that you're expecting though, if I had to guess :)

pyb
  • 4,813
  • 2
  • 27
  • 45
Lyndsy Simon
  • 5,208
  • 1
  • 17
  • 21
  • This is a good answer for working with totally unknown objects. Python's use of dictionaries makes code like this not just possible, but highly readable. – TheSoundDefense Jul 14 '14 at 19:12
4

You can use vars builtin method to get a dictionary of the object's attributes:

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

Maybe combine it with pprint to get a somewhat formatted output:

>>> 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'>[]>,
  ...
famousgarkin
  • 13,687
  • 5
  • 58
  • 74
3

I'd recommend the inspect module:

import inspect
print inspect.getmembers(my_obj)

This includes the __dict__ but also includes details about all methods on the object, which can be very useful.

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
2

That is the most universal way to "print" an object, it's just that not every object will have a very useful printout; most probably don't, in fact.

If you're working with an object someone else created, you'll often want to look at the documentation to find out how to look at its variables and whatnot. That will often give you the prettiest output. Other answers to this question offer a more general way of inspecting an object, which can be a lot faster and easier than looking up documentation; they do a more shallow inspection, as far as I can tell, but they're a good starting point.

If you're making your own object, you'll want to define a method called __str__() that returns a string. Then, whenever you say print obj, that object's __str__() function will be called, and that string will be returned.

In your case, if you have a request.Session() object named my_obj, you can apparently print it with print(my_obj.text), according to the documentation.

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

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
  • Good catch with it being a Requests Session object! – Lyndsy Simon Jul 14 '14 at 19:08
  • 3
    This answer isn't wrong, but it doesn't answer the OP's question about *inspection* at all. – Lukas Graf Jul 14 '14 at 19:18
  • 1
    Ruby works the same way. The method `p` calls the `to_s` method. If the programmer has not overridden the `to_s` that the object inherited (from `Object`), you end up with something like #. Most (all?) classes that Ruby ships with do override `to_s`. – steenslag Jul 14 '14 at 19:24
  • 1
    @steenslag Actually, `p` calls `inspect`, whereas `puts` calls `to_s`. – Daniël Knippers Jul 14 '14 at 19:46
-1

If you want complete control over printing for the object, define the __repr__ and __str__ functions for your class.

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

Sometimes you will want to see the detailed information, so only overwriting __str__ is probably a good idea.

Good details on the difference between repr and str here: Difference between __str__ and __repr__ in Python

Community
  • 1
  • 1
user1636615
  • 102
  • 5