9.8. Idiom Dir

9.8.1. SetUp

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def login(self):
...         return 'logged-in'
...
...     def logout(self):
...         return 'logged-out'

9.8.2. Class

>>> dir(User)
['__class__', '__delattr__', '__dict__', '__dir__',
 '__doc__', '__eq__', '__firstlineno__', '__format__',
 '__ge__', '__getattribute__', '__getstate__', '__gt__',
 '__hash__', '__init__', '__init_subclass__', '__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
 '__static_attributes__', '__str__', '__subclasshook__',
 '__weakref__', 'login', 'logout']

9.8.3. Instance

>>> mark = User('Mark', 'Watney')
>>>
>>> dir(mark)
['__class__', '__delattr__', '__dict__', '__dir__',
 '__doc__', '__eq__', '__firstlineno__', '__format__',
 '__ge__', '__getattribute__', '__getstate__', '__gt__',
 '__hash__', '__init__', '__init_subclass__', '__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
 '__static_attributes__', '__str__', '__subclasshook__',
 '__weakref__', 'firstname', 'lastname', 'login', 'logout']

9.8.4. Dir vs Vars

  • Function vars() returns variables only

  • Function dir() returns variables and methods

>>> mark = User('Mark', 'Watney')
>>>
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney'}
>>>
>>> dir(mark)
['__class__', '__delattr__', '__dict__', '__dir__',
 '__doc__', '__eq__', '__firstlineno__', '__format__',
 '__ge__', '__getattribute__', '__getstate__', '__gt__',
 '__hash__', '__init__', '__init_subclass__', '__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
 '__static_attributes__', '__str__', '__subclasshook__',
 '__weakref__', 'firstname', 'lastname', 'login', 'logout']

9.8.5. Public Attributes

>>> [attrname
...  for attrname in dir(mark)
...  if not attrname.startswith('_')]
...
['firstname', 'lastname', 'login', 'logout']

9.8.6. Public Methods

>>> [attrname
...  for attrname in dir(mark)
...  if not attrname.startswith('_')
...  and callable(getattr(mark, attrname))]
...
['login', 'logout']

9.8.7. Public Variables

>>> [attrname
...  for attrname in dir(mark)
...  if not attrname.startswith('_')
...  and not callable(getattr(mark, attrname))]
...
['firstname', 'lastname']

Rationale:

>>> result = getattr(mark, 'firstname')
>>> result
'Mark'
>>> result = getattr(mark, 'login')
>>> result()
'logged-in'