laike9m / pdir2

Pretty dir() printing with joy:beer:
MIT License
1.33k stars 47 forks source link

AttributeError when checking instances with __slots__ #44

Closed liwt31 closed 5 years ago

liwt31 commented 5 years ago

Code to reproduce the error:

import pdir

class A():
    __slots__ = ['a']

a = A()
pdir(a)

Error message:

Traceback (most recent call last):
  File "/export/home/weitangli/GitClone/pdir2/pdir/api.py", line 165, in __getattr_wrapper
    return get_dict_attr(self.obj, name)
  File "/export/home/weitangli/GitClone/pdir2/pdir/utils.py", line 4, in get_dict_attr
    if attr in obj.__dict__:
AttributeError: 'A' object has no attribute '__dict__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    pdir(a)
  File "/export/home/weitangli/GitClone/pdir2/pdir/api.py", line 43, in __init__
    attr = self.__getattr_wrapper(name)
  File "/export/home/weitangli/GitClone/pdir2/pdir/api.py", line 167, in __getattr_wrapper
    return getattr(self.obj, name)
AttributeError: a

This is because even though 'a' is not defined for a, it is still in its __dir__() due to the mechanism of __slots__:

In [3]: dir(a)                                                                                                                                                                                                                                               
Out[3]: 
['__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__slots__',
 '__str__',
 '__subclasshook__',
 'a']

In [4]: getattr(a, 'a')                                                                                                                                                                                                                                      
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-7cba3fe09424> in <module>
----> 1 getattr(a, 'a')

AttributeError: a