Created
December 1, 2019 22:43
-
-
Save lorne-luo/16f1336c8aef29737b29d8713d8e830c to your computer and use it in GitHub Desktop.
Python meta example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import types | |
from functools import wraps | |
from abc import ABCMeta | |
def timeit(f): | |
@wraps(f) | |
def wrapper(*args, **kwargs): | |
start = time.time() | |
resp = f(*args, **kwargs) | |
end = time.time() | |
return (resp, end - start) | |
return wrapper | |
# A metaclass that replaces methods of its classes | |
class TimeMeta(type): | |
def __new__(cls, name, bases, attr, *args, **kwargs): | |
# def __new__(*args, **kwargs): # real signature unknown | |
# print(args) | |
# print(kwargs) | |
# Replace each function with a decorated version of the function | |
for name, value in attr.items(): | |
print('#',name,value) | |
if type(value) is types.FunctionType or type(value) is types.MethodType: | |
attr[name] = timeit(value) | |
# Return a new type called TimeMeta | |
return super(TimeMeta, cls).__new__(cls, name, bases, attr) | |
# Test the metaclass | |
class Animal(metaclass=TimeMeta): | |
def talk(self): | |
time.sleep(1) | |
print("Animal talk") | |
class Cow(Animal): | |
def talk(self): | |
time.sleep(1) | |
print("Moo") | |
if __name__ == '__main__': | |
animal = Animal() | |
cow = Cow() | |
print(type(animal)) | |
print(type(cow)) | |
print(animal.talk()) | |
print(cow.talk()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment