1

I am trying to override class attribute access in python3. I found this question already answered for python2. But the same is not working with Python3. Please help me to understand why this does not work with Python3 and how to get it to work.

Here is the code i am trying to verify in Python3:

class BooType(type):
    def __getattr__(self, attr):
        print(attr)
        return attr

class Boo(object):
    __metaclass__ = BooType

boo = Boo()
Boo.asd     #Raises AttributeError in Python3 where as in Python2 this prints 'asd'
goDDu
  • 45
  • 6

1 Answers1

0

from http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Metaprogramming.html

Python 3 changes the metaclass hook. It doesn’t disallow the __metaclass__ field, but it ignores it. Instead, you use a keyword argument in the base-class list:

in your case, you have to change to:

class Boo(object, metaclass = BooType):
    pass

and that works. This syntax isn't compatible with python 2, though.

There's a way to create compatible code, seen in http://python-future.org/compatible_idioms.html#metaclasses

# Python 2 and 3:
from six import with_metaclass
# or
from future.utils import with_metaclass

class Boo(with_metaclass(BooType, object)):
    pass
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219