Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pypy specific error

Tags:

python

pypy

I have the following code:

#!/usr/bin/env python
#!/usr/bin/env pypy

class my_components(object):
    COMP0 = 0
    COMP1 = 1
    COMP1 = 2
    __IGNORECOMP = -1

def attribute_dictionary(o):
    d = { }
    for attr in dir(o):
        if attr[:2] != '__':
            print o,attr
            d[attr] = o.__getattribute__(o, attr)
    return d

def main():
    print attribute_dictionary(my_components)

if __name__ == '__main__':
    main()

that I use to effectively do fancy enum in python.

It works great in python, prints:

<class '__main__.my_components'> COMP0
<class '__main__.my_components'> COMP1
<class '__main__.my_components'> _my_components__IGNORECOMP
{'COMP0': 0, 'COMP1': 2, '_my_components__IGNORECOMP': -1}

However, when I run it with pypy (switch first two lines) it fails with:

<class '__main__.my_components'> COMP0
Traceback (most recent call last):
  File "app_main.py", line 53, in run_toplevel
  File "./pypy_Test.py", line 25, in <module>
    main()
  File "./pypy_Test.py", line 21, in main
    print attribute_dictionary(my_components)
  File "./pypy_Test.py", line 17, in attribute_dictionary
    d[attr] = o.__getattribute__(o, attr)
TypeError: unbound method __getattribute__() must be called with my_components instance as first argument (got type instance instead)

Any insights would be most welcome.

-Thanks

like image 447
vkontori Avatar asked May 27 '26 07:05

vkontori


2 Answers

You are calling __getattribute__ passing in the class, not an instance of that class. From the __getattribute__ documentation:

Called unconditionally to implement attribute accesses for instances of the class.

The fact that this works at all with the class as a first argument in cPython is a happy coincidence; officially, the first argument should be an instance instead.

like image 161
Martijn Pieters Avatar answered May 30 '26 05:05

Martijn Pieters


TypeError: unbound method __getattribute__() must be called with my_components instance as first argument (got type instance instead)

This is saying that (at least with PyPy), the first argument to __getattribute__ must be an instance of the class my_components.

Instead, o is the class my_components itself, not an instance.

Try changing

d[attr] = o.__getattribute__(o, attr)

to

d[attr] = getattr(o, attr)
like image 36
unutbu Avatar answered May 30 '26 05:05

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!