Search code examples
pythonpprint

Python pprint issues


I'm using the User object from the Google App Engine environment, and just tried the following:

pprint(user)
print vars(user)

The results:

pprint(user)

users.User(email='[email protected]',_user_id='18580000000000')

print vars(user)

{'_User__federated_identity': None, '_User__auth_domain': 'gmail.com',
'_User__email': '[email protected]', '_User__user_id': '1858000000000',
'_User__federated_provider': None}

Several issues here (sorry for the multipart):

  1. How come I'm not seeing all the variables in my object. It's not showing auth_domain, which has a value?
  2. Is there a way to have it list properties that are = None? None is a legitimate value, why does it treat those properties like they don't exist?
  3. Is there a way to get pprint to line-break between properties?

Solution

  • pprint is printing the repr of the instance, while vars simply returns the instance's __dict__, whose repr is then printed. Here's an example:

    >>> class Foo(object):
    ...     def __init__(self, a, b):
    ...             self.a = a
    ...             self.b = b
    ...     def __repr__(self):
    ...             return 'Foo(a=%s)' % self.a
    ...
    >>> f = Foo(a=1, b=2)
    >>> vars(f)
    {'a': 1, 'b': 2}
    >>> pprint.pprint(f)
    Foo(a=1)
    >>> vars(f) is f.__dict__
    True
    

    You see that the special method __repr__ here (called by pprint(), the print statement, repr(), and others) explicitly only includes the a member, while the instance's __dict__ contains both a and b, and is reflected by the dictionary returned by vars().