Showing posts with label python_metaclass. Show all posts
Showing posts with label python_metaclass. Show all posts

Apr 21, 2017

[python] metaclass flow

#!/bin/env python


class MetaType(type):

    def __new__(cls, name, bases, attrs):
        print("in meta new")
        print("name: " + name)
        print("bases: " + str(bases))
        print("attrs: " + str(attrs))
        print("klas info: " + str(cls.__class__))
        #  return type(name, bases, attrs)
        #  Above code will lose metatype info,
        #  which De will be built by 'type', not this MetaType.
        return type.__new__(cls, name, bases, attrs)

    def __init__(cls, name, bases, attrs):
        # cls is returned by this def __new__
        print("in meta init")
        print(dir(cls))

    def __call__(cls, *args, **kwargs):
        print("In meta call")
        # will call type instance's __new__ and __init__
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Base(object):
    __metaclass__ = MetaType

    def __new__(cls):
        print("in base new")
        print(cls.__class__)  # Print MetaType
        return super(Base, cls).__new__(cls)

    def __init__(self, opt):
        print("Base init")


class De(Base):

    def __new__(cls, input):
        print("in De new")
        print(cls.__class__)  # Print MetaType
        #  return super(Base, cls).__new__(cls) # will bypass Base's __new__
        return super(De, cls).__new__(cls)

    def __init__(self, input):
        print("De init")

    def testFunc(self):
        pass


if __name__ == "__main__":
    """
    1. Constructing Base type instance.
    2. Call MetaType __new__, must return with type.__new__, otherwise using
        type(...) with lose the metaclass info.
    3. Call MetaType __init__
    4. Call MetaType __new__, must return with type.__new__, otherwise using
        type(...) with lose the metaclass info.
        This time with 'De's info.
    5. Call MetaType __init__
    6. Since we call De("hi"), now call MetaType's def __call__
        inside it should call type.__call__ to trigger
        calling MetaType's instance's(aka. De) __new__ and __init__
    7. De's __new__ should call super in order to trigger base instance's
        __new__
    8. De's __init__ should call super in order to trigger base instance's
        __init__
    """
    a = De("hi")

-----------
in meta new
name: Base
bases: (<type 'object'>,)
attrs: {'__module__': '__main__', '__metaclass__': <class '__main__.MetaType'>, '__new__': <function __new__ at 0x7fe775497c80>, '__init__': <function __init__ at 0x7fe775497cf8>}
klas info: <type 'type'>
in meta init
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
in meta new
name: De
bases: (<class '__main__.Base'>,)
attrs: {'__module__': '__main__', 'testFunc': <function testFunc at 0x7fe775497e60>, '__new__': <function __new__ at 0x7fe775497d70>, '__init__': <function __init__ at 0x7fe775497de8>}
klas info: <type 'type'>
in meta init
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'testFunc']
In meta call
in De new
<class '__main__.MetaType'>
in base new
<class '__main__.MetaType'>
De init

Jan 4, 2017

[python] difference between type(), type.__new__()

difference between type(), type.__new__()


>>> class MetaA(type):
...     def __new__(cls, name, bases, dct):
...         print 'MetaA.__new__'
...         return type(name, bases, dct)
...     def __init__(cls, name, bases, dct):
...         print 'MetaA.__init__'
... 
>>> class A(object):
...     __metaclass__ = MetaA
... 
MetaA.__new__
>>> class MetaA(type):
...     def __new__(cls, name, bases, dct):
...         print 'MetaA.__new__'
...
...         # type.__new__() will call MetaA's __init__ to initialize it
...         return type.__new__(cls, name, bases, dct)
...     def __init__(cls, name, bases, dct):
...         print 'MetaA.__init__'
... 
>>> class A(object):
...     __metaclass__ = MetaA
... 
MetaA.__new__
MetaA.__init__

May 5, 2016

[python] metaclass used to create derived type instance.

Reference:
http://stackoverflow.com/a/6581949

Python does the following:


  • Is there a __metaclass__ attribute in Foo?
  • If yes, create in memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__.
  • If Python can't find __metaclass__, it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).
  • Then if it can't find any __metaclass__ at all, it will use the Bar's (the first parent) own metaclass (which might be the default type) to create the class object.
  • Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent (Bar.__class__) will be. 
    • If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__()), the subclasses will not inherit that behavior.


"""
Metaclass code explain
"""


class ModelMeta(type):
    def __new__(cls, name, bases, attrs):
        print("in new")
        print(name)  # Test2
        print(bases)  # (<class '__main__.Test'>,)
        print(cls)  # <class '__main__.ModelMeta'>

        """
        If not using type.__new__, derived class won't use
        metaclass to create type instance.
        """
        result = type.__new__(cls, name, bases, attrs)
        # result = type(name, bases, attrs)
        print(dir(result))
        """
            ['__class__', '__delattr__', '__dict__', '__doc__',
            '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__',
            '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
            '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
        """
        print(result.__metaclass__)  # <class '__main__.ModelMeta'>
        return result

    def __call__(cls, *args, **kwargs):
        print("in call")
        print(cls)
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Test(object):
    __metaclass__ = ModelMeta


class Test2(Test):
    pass


class Test3(Test2):
    pass

if __name__ == "__main__":
    t2 = Test2()  # call ModelMeta. __call__






Another perspect

"""
Metaclass code explain
"""


class ModelMeta(type):
    def __new__(cls, name, bases, attrs):
        print("in new")
        print("name:{0}".format(name))  # Test2
        print("bases:{0}".format(bases))  # (<class '__main__.Test'>,)
        print("cls:{0}".format(cls))  # <class '__main__.ModelMeta'>
        print("attrs:{0}".format(attrs))  # <class '__main__.ModelMeta'>
        # Class Test 將擁有空的bases集合
        parents = [b for b in bases if isinstance(b, ModelMeta)]
        print("parents:{0}".format(parents))
        """
        If not using type.__new__, derived class won't use
        metaclass to create type instance.
        """
        result = type.__new__(cls, name, bases, attrs)
        # there will be no inheritence affect if using simply type constructor
        # result = type(name, bases, attrs)
        print(dir(result))
        """
            ['__class__', '__delattr__', '__dict__', '__doc__',
            '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__',
            '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
            '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
        """
        print(result.__metaclass__)  # <class '__main__.ModelMeta'>
        return result

    def __call__(cls, *args, **kwargs):
        print("in call")
        print(cls)
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Test(object):
    __metaclass__ = ModelMeta
    aa = 1


class Test2(Test):
    a = 2


class Test3(Test2):
    a = 3

if __name__ == "__main__":
    t2 = Test2()  # call ModelMeta. __call__
    print(t2.a)